- Author:
- grahamu
- Posted:
- February 28, 2007
- Language:
- Python
- Version:
- Pre .96
- Tags:
- newforms foreignkey dropdown choicefield form_for_model form_for_instance
- Score:
- 3 (after 3 ratings)
Using newforms you can create forms from existing models easily and automatically with either form_for_model(class)
or form_for_instance(instance)
. Usually the automagically generated form fields are sufficient; however, sometimes you need to restrict selections in a choice field.
You can also set the default selection when instantiating the form. In this example, if acct
is not contained in the 'account' field choices, the selection defaults to the first entry.
This example is probably not good practice when using form_for_instance
because the existing value 'selection' of the choice field is lost and must be reset manually (see above).
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
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 8 months ago
- Crispy Form by sourabhsinha396 8 months, 3 weeks ago
- ReadOnlySelect by mkoistinen 9 months, 1 week ago
- Verify events sent to your webhook endpoints by santos22 10 months ago
- Django Language Middleware by agusmakmun 10 months, 2 weeks ago
Comments
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
#
Please login first before commenting.