如何使用modelForms中的额外字段来查询对象?Djang

2024-04-23 16:03:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下表格:

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中查询完全相同的内容,它将返回我的对象。有什么想法吗


Tags: selfformfieldsgetrequestdefrecipeforms
1条回答
网友
1楼 · 发布于 2024-04-23 16:03:40

您应该访问已清理的数据,而不是字段

aux = form.cleaned_data['ingredient_form']

还要注意的是,您应该在类级别定义该字段,然后根本不需要定义__init__

class Recipe_IngredientForm(forms.ModelForm):
    ingredient_form = forms.CharField()
    class Meta:
        model = Recipe_Ingredient
        fields = ('quantity', 'quantityUnit')

相关问题 更多 >