views:

60

answers:

2

I am trying to use the ModelForm to add my data. It is working well, except that the ForeignKey dropdown list is showing all values and I only want it to display the values that a pertinent for the logged in user.

Here is my model for ExcludedDate, the record I want to add:

class ExcludedDate(models.Model):
date = models.DateTimeField()
reason = models.CharField(max_length=50)
user = models.ForeignKey(User)
category = models.ForeignKey(Category)
recurring = models.ForeignKey(RecurringExclusion)
def __unicode__(self):
    return self.reason

Here is the model for the category, which is the table containing the relationship that I'd like to limit by user:

class Category(models.Model):
name = models.CharField(max_length=50)
user = models.ForeignKey(User, unique=False)
def __unicode__(self):
    return self.name

And finally, the form code:

class ExcludedDateForm(ModelForm):
class Meta:
    model = models.ExcludedDate
    exclude = ('user', 'recurring',)

How do I get the form to display only the subset of categories where category.user equals the logged in user?

A: 

Hi! Here example:

models.py

class someData(models.Model):
    name = models.CharField(max_length=100,verbose_name="some value")

class testKey(models.Model):
    name = models.CharField(max_length=100,verbose_name="some value")
    tst = models.ForeignKey(someData)

class testForm(forms.ModelForm):
    class Meta:
        model = testKey

views.py

...
....
....
    mform = testForm()
    mform.fields["tst"] = models.forms.ModelMultipleChoiceField(queryset=someData.objects.filter(name__icontains="1"))
...
...

Or u can try something like this:

class testForm(forms.ModelForm):
    class Meta:
        model = testKey

def __init__(self,*args,**kwargs):
    super (testForm,self ).__init__(*args,**kwargs)
    self.fields['tst'].queryset = someData.objects.filter(name__icontains="1")
Saff
That will probably work but it's a bad practice. You shouldn't hack the form outside of the form class. It's much simpler to define this logic in __init__
Béres Botond
Yeah...I agree.. Already update my post.
Saff
+1  A: 

You can customize your form in init

class ExcludedDateForm(ModelForm):
    class Meta:
        model = models.ExcludedDate
        exclude = ('user', 'recurring',)
    def __init__(self, user=None, **kwargs):
        super(ExcludedDateForm, self).__init__(**kwargs)
        if user:
            self.fields['category'].queryset = models.Category.objects.filter(user=user)

And in views, when constructing your form, besides the standard form params, you'll specify also the current user:

form = ExcludedDateForm(user=request.user)
Béres Botond
This worked "easy as pie!" I appreciate not only your response, but the completeness of your answer.
malandro95
Glad to be of help :)
Béres Botond
So.... while the form now looks great, the change broke the view that adds the data. Any ideas? (code below)
malandro95
def excluded_date_add(request): print(request.user) if request.method == 'POST': excluded_date = ExcludedDate(user=request.user) form = ExcludedDateForm(request.POST, instance=excluded_date) print("before if") print(request.user) if form.is_valid(): print("after if") excluded_date = form.save() return HttpResponseRedirect('/excluded_dates/') else: form = ExcludedDateForm(user=request.user) return render_to_response('excluded_date_form.html', {'form': form})
malandro95
@malandro95: When you are creating your form instance with request.POST, it appears that you're not passing in user.
Ryan Duffield