Как использовать дополнительное поле из modelForms для запроса объекта? Джанго - PullRequest
0 голосов
/ 19 ноября 2018

У меня есть следующая форма:

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, и если я запрашиваю ту же самую вещь в оболочке, она возвращает мой объект. Любая идея?

1 Ответ

0 голосов
/ 19 ноября 2018

Вы должны обращаться к cleaned_data, а не к полям.

aux = form.cleaned_data['ingredient_form']

Также обратите внимание, что вы должны определить это поле на уровне класса, тогда вам вообще не нужно определять __init__.

class Recipe_IngredientForm(forms.ModelForm):
    ingredient_form = forms.CharField()
    class Meta:
        model = Recipe_Ingredient
        fields = ('quantity', 'quantityUnit')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...