我有以下表格:
class Recipe_IngredientForm(forms.ModelForm):
class Meta:
model = Recipe_Ingredient
fields = ('quantity', 'quantityUnit')
def __init__(self, *args, **kwargs):
super(Recipe_IngredientForm, self ).__init__(*args, **kwargs)
self.fields['ingredient_form'] = forms.CharField()
我试图获取这个表单的值来搜索一个对象,如果它存在,我会将它设置为保存在我的模型中
def recipe_add_ingredient(request, pk):
recipe = get_object_or_404(Recipe, pk=pk)
if request.method == "POST":
form = Recipe_IngredientForm(request.POST)
if form.is_valid():
recipeIngredient = form.save(commit=False)
recipeIngredient.recipe = recipe
aux = form.fields['ingredient_form']
recipeIngredient.ingredient = Ingredient.objects.get(name=aux)
recipeIngredient.save()
return redirect('recipe_detail', pk=recipe.pk)
else:
form = Recipe_IngredientForm()
return render(request, 'recipe/recipe_add_ingredient.html', {'form': form})
但是我在提交表单时遇到了一个错误:Ingredient matching query does not exist
,但它表明我通过get获得了一个存在的值,如果我在shell中查询完全相同的内容,它将返回我的对象。有什么想法吗
您应该访问已清理的数据,而不是字段
还要注意的是,您应该在类级别定义该字段,然后根本不需要定义
__init__
相关问题 更多 >
编程相关推荐