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?
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With