Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, adding excluded properties to the submitted modelform

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() method because the created_by is empty.

I've tried to add the user id to the form before the save() method like this: form.cleaned_data['created_by'] = 1 and form.cleaned_data['created_by_id'] = 1. But none of this works.

Can someone explain to me how I can 'add' additional stuff to the submitted modelform so that it will save?

class Location(models.Model):
    name = models.CharField(max_length = 100)
    created_by = models.ForeignKey(User)
    create_date = models.DateTimeField(auto_now=True)

class LocationForm(forms.ModelForm):
    class Meta:
        model = Location
        exclude = ('created_by', 'create_date', )
like image 204
Sven van Zoelen Avatar asked Apr 29 '11 12:04

Sven van Zoelen


1 Answers

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()
like image 57
Konstant Avatar answered Oct 09 '22 00:10

Konstant