[英]How to get the foreign keys related to drop down only of that user in Django ModelForm
I have Category
model like this: 我有这样的
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"
In my forms.py
: 在我的
forms.py
:
class CategoryForm(ModelForm):
class Meta:
model = Category
exclude = ['user']
class TaskForm(ModelForm):
class Meta:
model = Task
exclude = ['owner']
# views
form = TaskForm()
When I call {{ form }}
in template, it shows categories created by all the users. 当我在模板中调用
{{ form }}
时,它显示了所有用户创建的类别。 But I want to show the category created by only the logged in user. 但我想显示仅由登录用户创建的类别。 How to do that?
怎么做?
Try following: 请尝试以下操作:
form = TaskForm()
form.fields['owner'].queryset = Task.objects.filter(owner=request.user)
Or modify TaskForm
as follow if it is used multiple times: 如果多次使用
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)
then, pass request.user
: 然后,传递
request.user
:
form = TaskForm(request.user)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.