views:

290

answers:

1

Can anyone tell me how i can limit the choices for the Page model which i inherit from in the following code?

class CaseStudy(Page):
    """ 
    An entry in a fancy picture flow widget for a case study page
    """
    image = models.ForeignKey(Image, limit_choices_to={'is_active': True, 'category__code':'RP'})

    def __unicode__(self):
        return u"%s" % self.title

The django admin is limiting the image choices in a drop down successfully, but i would like to limit a field in the Page model as well (a 'parent page field'), ie:

class Page(models.Model):
    parent              = models.ForeignKey('self', blank=True, null=True, related_name='children')
A: 

I managed to work this out - by overriding the admin model form. I realise this could be tightened up, but thought it might come in use to someone out there. Here's an excerpt from the admin.py

class CaseStudyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CaseStudyForm, self).__init__(*args, **kwargs)

        recent_project_page = Page.objects.get(title="Recent Projects")        
        parent_widget = self.fields['parent'].widget
        choices = []
        for key, value in parent_widget.choices:
            if key in [recent_project_page.id,]:
                choices.append((key, value))
        parent_widget.choices = choices


class CaseStudyAdmin(admin.ModelAdmin):
    form = CaseStudyForm

admin.site.register(CaseStudy, CaseStudyAdmin)
stephendwolff