Django, adding excluded properties to the submitted modelform

前端 未结 4 2024
离开以前
离开以前 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: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()
    

提交回复
热议问题