Useful form tricks in Django

July 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)

or just

form = ChoiceForm(request.user)

3) Nothing yet, may expand this later.

About these ads

9 Comments

  1. thanks for the hints!

  2. I’m looking to use tip 2, but when i do i get the following error
    Exception Value: name ‘request’ is not defined

    I have recreated the example and used your tips exactly. I’m using django 1.0.

    Thanks

  3. Well you can only use tip 2 when you’re in a view or another place with request available, of course :)

  4. Is it possible then to use this to overwrite a form in the admin?

  5. Thank you so much! I was about to manually create a form, and I stumbled upon your page. Tip #2 is a life saver. It should be front and center in the django documentation.

    Thank you for your help!

    -Arash

  6. This helped me out immensely! Thanks for posting this. I did not think to override the field in the init method, unlike suggested in the Django docs.

  7. thanks for your post– #2 was also really helpful for me. FWIW, i dont know if this is a change is django implementation or not, but i had to explicitly call my form with request.user.username, since request.user is the entire user object (which still prints as ‘username’ because presumably it has the __unicode__ method defined).

    anyway, many thanks!

  8. You would only have to change it if you used a CharField with the username for the ‘owner’ field for some god awful reason – it should be a ForeignKey to User

  9. I was looking all over for something like this, thanks!


Sorry, the comment form is closed at this time.

Blog at WordPress.com. | The Pool Theme.
Entries and comments feeds.

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: