如何使用 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
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屋!