Django, adding excluded properties to the submitted modelform

前端 未结 4 2025
离开以前
离开以前 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:08

    The correct solution is to pass an instance of the object with pre-filled fields to the model form's constructor. That way the fields will be populated at validation time. Assigning values after form.save() may result in validation errors if fields are required.

    LocationForm(request.POST or None, instance=Location(
        created_by=request.user,
        create_date=datetime.now(),
    ))
    

    Notice that instance is an unsaved object, so the id will not be assigned until form saves it.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-05 23:29

    One way to do this is by using form.save(commit=False) (doc)

    That will return an object instance of the model class without committing it to the database.

    So, your processing might look something like this:

    form = some_form(request.POST)
    location = form.save(commit=False)
    user = User(pk=1)
    location.created_by = user
    location.create_date = datetime.now()
    location.save()
    
    0 讨论(0)
  • 2021-02-05 23:31

    Since you have excluded the fields created_by and create_date in your form, trying to assign them through form.cleaned_data does not make any sense.

    Here is what you can do:

    If you have a view, you can simply use form.save(commit=False) and then set the value of created_by

    def my_view(request):
        if request.method == "POST":
            form = LocationForm(request.POST)
            if form.is_valid():
                obj = form.save(commit=False)
                obj.created_by = request.user
                obj.save()
            ...
            ...
    

    `

    If you are using the Admin, you can override the save_model() method to get the desired result.

    class LocationAdmin(admin.ModelAdmin):
        def save_model(self, request, obj, form, change):
            obj.created_by = request.user
            obj.save()
    
    0 讨论(0)
提交回复
热议问题