Use a form with a custom __init__ in Django Admin

前端 未结 1 1108
臣服心动
臣服心动 2021-01-19 20:48

I use the code below to add a custom form in Django Admin:

class MyAdmin(admin.ModelAdmin):
    form = MyForm

However, the form has an over

相关标签:
1条回答
  • 2021-01-19 21:18

    change your MyAdmin class like this:

    class MyAdmin(admin.ModelAdmin):
        form = MyForm
    
        def get_form(self, request, **kwargs):
            form = super(MyAdmin, self).get_form(request, **kwargs)
            form.current_user = request.user
            return form
    

    You can now access the current user in your forms.ModelForm by accessing self.current_user.

    def __init__(self, author, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.author = author
        # access to current user by self.current_user
    
    0 讨论(0)
提交回复
热议问题