Filtering choices in Django's ModelForm

Published at 04, June 2010, author art. Tags: django, python, snippet

# ...
# There are models Subscription and MailList defined above.
# MailList has a many to many field 'managers'. This field
# defines which manager is able to edit/add subscriptions to
# a maillist.
# 
# To filter choices in the Django's admin, I use following code:

class SubscriptionAdmin(admin.ModelAdmin):
    list_display = ('id', 'mail_list', 'email', 'name')

    def get_form(self, request, obj=None, **kwargs):
        form_class = super(SubscriptionAdmin, self).get_form(request, obj = obj, **kwargs)

        class ModelFormWithPermissions(form_class):
            def __init__(self, *args, **kwargs):
                super(ModelFormWithPermissions, self).__init__(*args, **kwargs)

                self.fields['mail_list'].queryset = \ 
                    MailList.objects.filter(
                        managers__id = request.user.id
                    )   

        return ModelFormWithPermissions

site.register(Subscription, SubscriptionAdmin)

# This code creates a special ModelForm class which know
# about the current user, his 'id' and permissions.

Here is a gist file.

Pingbacks

permalink

04, June 2010, pingback from http://topsy.com/trackback?utm_source...:

Filtering choices in Django's ModelForm — Lazy Crazy Coder's blog

Comments

Subscribe on this post's comments

No comments. Wanna be first?

First, identify yourself and come back to leave comments.

If you wish to leave comment, please, identify yourself and then come back to this page.