meepmeep
meepmeep

Reputation: 3118

Django - restricting ChoiceField in form

Using Django 1.1.1

In models.py:

class Site(models.Model):
    name = models.CharField(max_length=50)

class SiteMonth(models.Model):
    site = models.ForeignKey(Site)
    timestamp = models.DateTimeField()
    parameter1 = models.IntegerField()
    ....

In site_view.py:

#form for selecting which site to analyse
class SiteForm(forms.Form):
    site = forms.ModelChoiceField(queryset=Site.objects.all())

#form for selecting which site month to analyse
class SiteMonthForm(forms.Form):
    month = forms.ModelChoiceField(queryset=SiteMonth.objects.all())

def site(request,site=None):
    siteForm = SiteForm(request.GET)
    if not site==None:
        siteMonthForm = SiteMonthForm(request.GET)
        .....

And in urls.py:

(r'^site/$', 'my_project.site_view.site'),
(r'^site/(?P<site>\d+)/', 'my_project.site_view.site'),

So what I'm doing is making a page which can be used to look at the details of a particular Site. If no site id is given in the url, a form exists to select one, which will then redirect to the right url (via javascript in the template).

What I want to do, once a Site is selected, is to have a form in the page permitting selection of the SiteMonth objects belonging to that site for further investigation. My code above currently lists all SiteMonth objects for all sites. How do I set the SiteMonth form to only populate with values relating to the site id given in the GET request?

I can think of a couple of ways to do this, neither particularly elegant - what's the proper django way?

Upvotes: 1

Views: 1810

Answers (1)

KillianDS
KillianDS

Reputation: 17176

Change the SiteMonthForm to something like this:

class SiteMonthForm(forms.Form):
    month = forms.ModelChoiceField(queryset=SiteMonth.objects.all())
    def __init__(self, site, *args, **kwargs):
        super(SiteMonthForm, self).__init__(*args, **kwargs)
        self.fields["month"].queryset = SiteMonth.objects.filter(site__id=site)

And use it like this:

def site(request,site=None):
    siteForm = SiteForm(request.GET)
    if not site==None:
        siteMonthForm = SiteMonthForm(site, request.GET)

Upvotes: 4

Related Questions