Django 1.3 CreateView/ModelForm and dynamic filtering of fields

154 views
Skip to first unread message

Paul Walsh

unread,
Jul 31, 2011, 2:35:47 PM7/31/11
to django...@googlegroups.com
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.

Specifically, my users need to add Subscribers, and each Subscriber has a m2m field that assigns him/her to a SubscriberList. When the form to create a subscriber loads for a given user, I need to options in subscriber_list to be filtered for that user's lists only. 

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, for eg., def __init__(self, user=request.user, **kwargs), 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.

Paul Walsh

unread,
Aug 2, 2011, 2:04:03 PM8/2/11
to django...@googlegroups.com
can anyone help with this?

thx.

Paul Walsh

unread,
Aug 6, 2011, 4:01:19 PM8/6/11
to django...@googlegroups.com
hmm. Still stuck on this. I have tried a range of solutions, but none work for me with 1.3 class-based views.

Can anyone help?
thx,

paul.
Reply all
Reply to author
Forward
0 new messages