tags:

views:

73

answers:

1

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?

+4  A: 

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)
KillianDS
that works perfectly, thank you!
meepmeep
while we're here, as its a similar question, do you know how I would set the chosen site to be pre-selected when the SiteForm is generated if a site has been chosen? Anything I try with 'initial' seems to have no effect.
meepmeep
@meepmeep: add something like `if not site in request.GET: request.GET.site = siteobject`. This will insert the site object in the GET querydict which can be further used by siteForm.
KillianDS