Modify fields created by form_for_model

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django.db import models
from django import newforms as forms
from django.contrib.auth.models import User

################ models ####################

class Account(models.Model):
    title = models.CharField(maxlength=30, blank=False)
    users = models.ManyToManyField(User, blank=True, null=True)
    is_active = models.BooleanField()

class Project(models.Model):
    title = models.CharField(maxlength=50, blank=False)
    account = models.ForeignKey(Account, blank=False)

################ views ####################

def add_project(request, acct=None):
    # get new Project form class
    FormClass = forms.models.form_for_model(Project)

    FormClass.base_fields['account'] = \
        forms.ModelChoiceField(queryset=Account.objects.filter(is_active=True))

    # set initial selection in the choice field
    form = FormClass(initial={'account': acct})

More like this

  1. Selectively change fields, widgets or labels in forms created from models by danjak 6 years, 3 months ago
  2. Add validation for 'unique' and 'unique_together' constraints to newforms created dynamically via form_for_model or form_for_instance by bikeshedder 6 years ago
  3. ingore_fields by RealNitro 5 years, 7 months ago
  4. form_for_model / instance customized save and model aware validation by fivethreeo 6 years, 1 month ago
  5. Natural language date/time form fields by jdriscoll 6 years ago

Comments

micampe (on March 5, 2007):

Wouldn't this be better resolved with a customized Manager class for the Account model?

#

mikeivanov (on April 16, 2007):

micampe, it's not better because filter parameters can be part of the user input.

#

pcollins (on August 30, 2007):

The code

FormClass.base_fields['account'] = forms.ModelChoiceField(queryset=Account.objects.filter(is_active=True))

has the side affect of losing any labeling magic that the model is doing for you (e.g. internationalization of the label). An alternative is to do

    FormClass.base_fields['account'].choices = [(a.id, str(a)) for a in Account.objects.filter(is_active=True)]

#

guettli (on March 3, 2008):

ModelForm is in django now:

ModelForm Documentation

#

(Forgotten your password?)