Django, adding excluded properties to the submitted modelform

前端 未结 4 2033
离开以前
离开以前 2021-02-05 22:50

I\'ve a modelform and I excluded two fields, the create_date and the created_by fields. Now I get the \"Not Null\" error when using the save()

4条回答
  •  暖寄归人
    2021-02-05 23:16

    Pass a user as a parameter to form constructor, then use it to set created_by field of a model instance:

    def add_location(request):
        ...
        form = LocationForm(user=request.user)
        ...
    
    class LocationForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            user = kwargs.pop('user')
            super(forms.ModelForm, self).__init__(*args, **kwargs)
            self.instance.created_by = user
    

提交回复
热议问题