3

I am trying to filter a field on a ModelForm. I am subclassing the generic CreateView for my view. I found many references to my problem on the web, but the solutions do not seem to work (for me at least) with Django 1.3's class-based views.

Here are my models:

#models.py

class Subscriber(models.Model):

    user = models.ForeignKey(User)
    subscriber_list = models.ManyToManyField('SubscriberList')
    ....

class SubscriberList(models.Model):

    user = models.ForeignKey(User)
    name = models.CharField(max_length=70)
....

Here is my view:

#views.py

class SubscriberCreateView(AuthCreateView):
    model = Subscriber
    template_name = "forms/app.html"
    form_class = SubscriberForm
    success_url = "/app/subscribers/"

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        return super(SubscriberCreateView, self).form_valid(form) 

Here is my original form for adding a Subscriber, with no filter:

#forms.py

class SubscriberForm(ModelForm):

    class Meta:
        model = Subscriber
        exclude = ('user', 'facebook_id', 'twitter_id')

Here is my modified form, attempting to filter, but doesn't work:

#forms.py

class SubscriberForm(ModelForm):

    class Meta:
        model = Subscriber
        exclude = ('user', 'facebook_id', 'twitter_id')

    def __init__(self, user, **kwargs):
        super(SubscriberForm, self).__init__(**kwargs)
        self.fields['subscriber_list'].queryset = SubscriberList.objects.filter(user=user)

If I change this modified form as so:

def __init__(self, user=None, **kwargs)

It works - It brings me NO subscriber lists. But any way I try to pass the request user, I invariably get a a name "request" or name "self" not defined error.

So, how can I modify my code to filter subscriber_list by the request.user, and still use Django 1.3's CreateView.

Vlad T.
  • 2,568
  • 3
  • 26
  • 40

1 Answers1

17

I see you've been posting this question in various places.. and the way I found that is because I was trying to figure out the same thing. I think I just got it working, and here's what I did. I overwrote get_form() from FormMixin to filter a specific form fields queryset:

class MyCreateView(CreateView):

    def get_form(self, form_class):
        form = super(MyCreateView,self).get_form(form_class) #instantiate using parent
        form.fields['my_list'].queryset = MyObject.objects.filter(user=self.request.user)
        return form
shawnwall
  • 4,549
  • 1
  • 27
  • 38
  • how is it that StackOverflow has a _link to my brain_ : Seeing my exact question answered is very nice, but seeing the answer dates from approximatively the day I had the same question is spooky. – makapuf Sep 01 '11 at 16:08
  • No need to override `get_form()` - https://stackoverflow.com/a/24043478/5675325. – Tiago Martins Peres Jul 22 '22 at 18:29