简体   繁体   中英

Set value of excluded field in django ModelForm programmatically

I have a ModelForm class where I want to exclude one of the fields ( language ) from the form and add it programmatically. I tried to add the language in the clean method, but got an IntegrityError ( "Column 'language_id' cannot be null" ). I assume this is because any data for language returned from clean() will be ignored since it's in the exclude tuple. I'm using the form in a ModelAdmin class. I haven't managed to find any way to deal with this, so any tips or hints will 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

What you can do is when you save the form in the view, you don't commit the data. You can then set the value of the excluded field programmatically. I run into this a lot when I have a user field and I want to exclude that field and set to the current user.

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

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

How I dealt with a similar case was by using HiddenInput rather than exclude.

ie

class DefaultLanguagePageForm(ModelForm):
    
    ...

    class Meta:
        model = Page
        exclude = []

        widgets = {
            "language": HiddenInput(attrs={"value": "temp_language"}),
        }

and then in the view or wherever I'd like to assign, it, just assign it eg

def save_form_view(self, request):
    form.cleaned_data["language"] = "en"

The attrs={"value": "temp_language"} is if you don't allow blank values in the model and you want to assign the value in a view using cleaned_data. The form validation would fail if the field is blank or uses "".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM