Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用modelForms中的额外字段来查询对象?德扬戈_Python_Django_Forms - Fatal编程技术网

Python 如何使用modelForms中的额外字段来查询对象?德扬戈

Python 如何使用modelForms中的额外字段来查询对象?德扬戈,python,django,forms,Python,Django,Forms,我有以下表格: 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) sel

我有以下表格:

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})

但是我在提交表单时遇到一个错误:
成分匹配查询不存在
,但它表明我正在通过get获取一个存在的值,如果我在shell中查询完全相同的内容,它将返回我的对象。有什么想法吗

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

aux = form.cleaned_data['ingredient_form']
还要注意的是,您应该在类级别定义该字段,那么您根本不需要定义
\uuuu init\uuuu

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

就这样!完美答案。