Useful form tricks in DjangoJuly 24, 2008 at 12:46 am | Posted in django | 9 Comments
Not much text to put in this post, I just want to show a few useful things you can do with a ModelForm in django, so I can quit retyping examples 🙂
1) Replace a widget without losing all the default values passed to the form field from the model definition:
from django import forms from mysite.polls.models import Poll class PollForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PollForm, self).__init__(*args, **kwargs) self.fields['question'].widget = forms.Textarea() class Meta: model = Poll
2) Along the same lines, limit the choices of a ForeignKey based on a user:
(assume we’ve added an owner field to the tutorial Poll model to indicate the User who created the Poll)
from datetime import datetime, timedelta from django import forms from mysite.polls.models import Poll, Choice class ChoiceForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(ChoiceForm, self).__init__(*args, **kwargs) self.fields['poll'].queryset = Poll.objects.filter(owner=user) class Meta: model = Choice
In this one, you would then call the form with request.user as the first argument:
form = ChoiceForm(request.user, request.POST)
form = ChoiceForm(request.user)
3) Nothing yet, may expand this later.
Sorry, the comment form is closed at this time.