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})
Comments
Wouldn't this be better resolved with a customized Manager class for the Account model?
#
micampe, it's not better because filter parameters can be part of the user input.
#
The code
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
#
ModelForm is in django now:
ModelForm Documentation
#