Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter values in a Django form using ModelForm?

Tags:

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?

like image 665
harwalan Avatar asked Jun 09 '10 22:06

harwalan


People also ask

How do I filter records in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

Can you filter by property Django?

Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.

What is ModelForm in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.


1 Answers

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) 
like image 158
Botond Béres Avatar answered Oct 04 '22 14:10

Botond Béres