dave
dave

Reputation: 683

Building Select Options in Django

I'd like to create a form that when viewed, the user's favorite fruits are queried from the database and displayed as follows:

<select size="4"> 
<option selected>Apples</option>
<option>Bananas</option> 
<option>Oranges</option>
<option>Watermelon</option> 
</select>

The view that uses the form will:

  1. Get the user object.
  2. Query the database for the user's favorite fruits. (Each is a separate object of the Fruit model.)
  3. Load the form with the fruit choices collected in (2).

I was considering using the ChoiceField, but it looks like you cannot load the list of choices into the form dynamically, at least in a straightforward manner. Am I better off skipping the form and generating the code directly at the template? Or is there a way to load the form's ChoiceField with the user items at the view?

Also, are there any general rules of thumb that dictate where it's easier to build a form using the django form fields vs generating the form code at the template?

Upvotes: 1

Views: 3804

Answers (3)

dave
dave

Reputation: 683

I found the answer in this stack overflow topic. The trick is to override the form __init__() so that it accepts a new keyword argument, which in this case is the user.

views.py snippet

context = RequestContext(request)
user = User.objects.get(username=context['user'])
form = forms.FruitForm(user=user)

forms.py snippet

from django import forms

class FruitForm(forms.Form):
    fruits = forms.ModelChoiceField(queryset=Fruit.objects.all())

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super(FruitForm, self).__init__(*args, **kwargs)
        if user:
            self.fields['fruits'].queryset = Fruit.objects.filter(user=user)

Upvotes: 5

Stefan Bossbaly
Stefan Bossbaly

Reputation: 6794

Create a Form or a ModelForm that will be used in you view. The differnce between the two classes is the the ModelForm is built to closely resemble a database model defined in your models.py file where a Form can have custom attributes.

from django.forms import ModelForm
class FruitForm(ModelForm):
    class Meta:
        model = User
        fields = ('favorite-fruits', )

Upvotes: 0

super9
super9

Reputation: 30101

It's not that difficult. You can accomplish this easily using a modelform.

See: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/

One of the strengths of the Django framework is it's form handling and validation methods. So if possible, it always better for you to use Django forms or model forms.

Upvotes: 0

Related Questions