如何使用ModelForm过滤Django表单中的值? [英] How do I filter values in a Django form using ModelForm?
问题描述
我正在尝试使用ModelForm来添加我的数据。它工作得很好,除了外键下拉列表显示所有值,我只希望它显示与登录用户相关的值。
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.
这里是我的模型为ExcludedDate,我要添加的记录:
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
最后,表单代码:
class ExcludedDateForm(ModelForm):
class Meta:
model = models.ExcludedDate
exclude = ('user', 'recurring',)
如何让表单只显示类别的子集其中category.user等于登录用户?
How do I get the form to display only the subset of categories where category.user equals the logged in user?
推荐答案
您可以在 init / p>
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)
这篇关于如何使用ModelForm过滤Django表单中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!