Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set value of excluded field in django ModelForm programmatically

Tags:

python

django

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
like image 802
Joar Leth Avatar asked Nov 28 '14 15:11

Joar Leth


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is form as_ p in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.

What is clean data in Django?

Eventually, the browser would will everything as strings. When Django cleans the data it automatically converts data to the appropriate type. For example IntegerField data would be converted to an integer In Django, this cleaned and validated data is commonly known as cleaned data.

What method can you use to check if form data has changed when using a form instance?

Use the has_changed() method on your Form when you need to check if the form data has been changed from the initial data. has_changed() will be True if the data from request.


1 Answers

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

like image 69
awwester Avatar answered Sep 23 '22 17:09

awwester