Set value of excluded field in django ModelForm programmatically

I have a ModelForm class where I want to exclude one of the ( language ) fields from the form and add it programmatically. I tried adding a language to a clean method, but got IntegrityError ( "Column 'language_id' cannot be null" ). I assume that this is due to the fact that any data for language returned from clean() will be ignored, since it should be excluded in the court. I use the form in the ModelAdmin class. I was not able to find a way to handle this, so any tips or tricks would be much appreciated.

 from django import forms from myapp import models from django.contrib import admin class DefaultLanguagePageForm(forms.ModelForm): def clean(self): cleaned_data = super(DefaultLanguagePageForm, self).clean() english = models.Language.objects.get(code="en") cleaned_data['language'] = english return cleaned_data class Meta: model = models.Page exclude = ("language",) class PageAdmin(admin.ModelAdmin): form = DefaultLanguagePageForm 
+5
source share
1 answer

What you can do is when you save the form in the view, you do not commit the data. Then you can programmatically set the value of the excluded field. I encounter this a lot when I have a user field, and I want to exclude this field and set for the current user.

 form = form.save(commit=False) form.language = "en" form.save() 

Here's a bit more info on commit = False -> https://docs.djangoproject.com/en/1.6/topics/forms/modelforms/#the-save-method

+5
source

Source: https://habr.com/ru/post/1207896/


All Articles