我正在开发一个django应用程序,它有一个用于创建成分的表单。表单包含用于选择食谱的下拉列表。当用户创建一个成分时,在下拉列表中,我希望只显示由同一用户创建的那些食谱。
这是我的代码:
#forms.py
class IngredientForm(forms.ModelForm):
primal = forms.BooleanField()
class Meta:
model = Ingredient
fields = ('recipe_id', 'title', 'instructions', 'rules')
#models.py
class Recipe(models.Model):
user = models.ForeignKey('auth.User')
title = models.CharField(max_length=500)
description = models.TextField(max_length=500)
rules = models.TextField(max_length=500,blank=True)
def __str__(self):
return self.title
class Ingredient(models.Model):
user = models.ForeignKey('auth.User')
recipe_id = models.ForeignKey(Recipe, on_delete=models.CASCADE)
title = models.CharField(max_length=500)
instructions = models.CharField(max_length=500)
rules = models.TextField(max_length=500,blank=True)
primal = models.CharField(default='0',max_length=500,blank=True)
def __str__(self):
return self.title
#views.py
def create_ingredient(request):
if request.method == 'POST':
form = IngredientForm(request.POST)
if form.is_valid():
current_user = request.user
data = form.cleaned_data
ingredient_data=Ingredient.objects.create(user=current_user, recipe_id=data['recipe_id'],title=data['title'], primal=data['primal'], instructions=data['instructions'], rules=data['rules'])
ingredient_data.save()
ingredient = Ingredient.objects.get(pk = ingredient_data.pk)
return redirect('ingredient_detail', pk=ingredient.pk)
else:
messages.error(request, "Error")
return render(request, 'create_ingredient.html', {'form': IngredientForm })
现在的问题是,当用户尝试选择食谱时,网站所有用户创建的食谱会显示在“recipe_id”下拉列表中。他应该只能看到自己创建的下拉菜单。任何想法怎么做?
答案更新:
如果我使用它:
...
if request.method == 'POST':
form = IngredientForm(current_user=request.user, request.POST)
if form.is_valid():
...
它在此行non-keyword arg after keyword arg
form = IngredientForm(current_user=request.user, request.POST)
更新#2:
如果我使用:
...
if request.method == 'POST':
form = IngredientForm( request.POST,current_user=request.user)
if form.is_valid():
...
它给了我错误:__init__() got multiple values of argument 'current.user'
如果我使用:
...
if request.method == 'POST':
form = IngredientForm( request.POST)
if form.is_valid():
...
它给了我错误:'QueryDict' object has no attribute 'id'
更新#3:
从答案中实施最新更新后。它给了我错误name 'current_user' is not defined
在下面的代码中:
def create_ingredient(request):
form = IngredientForm(current_user=request.user)
答案 0 :(得分:2)
在模型表格中,您可以这样做:
class IngredientForm(ModelForm):
primal = forms.BooleanField()
class Meta:
model = Ingredient
fields = ('recipe_id', 'title', 'instructions', 'rules')
def __init__(self, current_user, *args, **kwargs):
super(IngredientForm, self).__init__(*args, **kwargs)
self.fields['recipe_id'].queryset = self.fields['recipe_id'].queryset.filter(user=current_user.id)
然后像这样实例化表单
form = IngredientForm(current_user=request.user)
编辑#1:
将用户传递到POST请求表单:
if request.method == "POST":
form = IngredientForm(request.POST, current_user=request.user)
if form.is_valid():
....
编辑#2:
尝试将init decleration更改为以下内容并从kwargs弹出用户:
def __init__(self, *args, **kwargs):
current_user = kwargs.pop('current_user', None)
super(IngredientForm, self).__init__(*args, **kwargs)
if current_user:
self.fields['recipe_id'].queryset = self.fields['recipe_id'].queryset.filter(user=current_user.id)
我认为这可能会解决您的问题,请将其余代码与上面的答案(创建表单的地方)保持一致