我有Category
这样的模型:
class Task(models.Model):
'''
Task for the wedding plans
'''
description = models.CharField(max_length=128)
owner = models.ForeignKey(User, default="bride")
category = models.ForeignKey(Category)
class Category(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=128)
budget = models.DecimalField(default=0.0, decimal_places=2, max_digits=8, help_text="Amount in dollars ($)")
class Meta:
verbose_name_plural = "Categories"
在我的forms.py
:
class CategoryForm(ModelForm):
class Meta:
model = Category
exclude = ['user']
class TaskForm(ModelForm):
class Meta:
model = Task
exclude = ['owner']
# views
form = TaskForm()
当我在模板中调用{{ form }}
时,它会显示所有用户创建的类别。但我想显示仅由登录用户创建的类别。怎么做?
答案 0 :(得分:2)
请尝试以下操作:
form = TaskForm()
form.fields['owner'].queryset = Task.objects.filter(owner=request.user)
如果多次使用,请修改TaskForm
如下:
class TaskForm(ModelForm):
class Meta:
model = Task
exclude = ['owner']
def __init__(self, user, *args, **kwargs):
super(TaskForm, self).__init__(*args, **kwargs)
self.fields['owner'].queryset = Task.objects.filter(owner=user)
然后,传递request.user
:
form = TaskForm(request.user)