bcoughlan
bcoughlan

Reputation: 26627

Django - Restricting ModelChoiceField to valid values

Models.py:

class Comment(models.Model):
    user = models.ForeignKey(User)
    document = models.ForeignKey(Document)
    section = models.ForeignKey(Section, null=True, blank=True)
    description = models.TextField(null=True, blank=True)

Forms.py:

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ('section', 'description')

Each Comment belongs to a Section of a Document. Each Document hasmany Sections. However, the ModelChoiceField printed out by Django will contain Sections for ALL Documents.

How do I tell Django to only print the Sections that belong to a particular Document?

I looked at ModelFormSets - Changing the queryset but I don't think it's quite what I'm after.

Upvotes: 0

Views: 492

Answers (2)

digitaldreamer
digitaldreamer

Reputation: 55332

If all you need to do is adjust the admin site you can override the formfield_for_foreignkey method on your django admin class.

From the docs:

ModelAdmin.formfield_for_foreignkey(self,db_field, request, **kwargs)

The formfield_for_foreignkey method on a ModelAdmin allows you to override the default formfield for a foreign key field. For example, to return a subset of objects for this foreign key field based on the user:

class MyModelAdmin(admin.ModelAdmin):
     def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "car":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

This uses the HttpRequest instance to filter the Car foreign key field to only display the cars owned by the User instance.

Upvotes: 2

arie
arie

Reputation: 18972

I think you want to change the ModelChoiceField's queryset and not the queryset of the formset.

Upvotes: 1

Related Questions