django表单即使输入中有内容也返回None

时间:2018-07-25 21:37:20

标签: django python-3.x django-forms

您好,因此我一直在创建一个自定义表单int django,在我遇到此问题之前,一切都一直按照我认为的方式进行。因此,我创建了一个说明表格:

class InstructionForm(forms.Form):
    step = forms.IntegerField(widget=forms.HiddenInput(attrs={'value':1}))
    instruction = forms.CharField(widget=forms.Textarea)

我为此创建了一个表单集,以便我可以让用户添加任意​​数量的内容。

view.py

def create(request):
    recipeForm = RecipeForm()
    ingredientFormSet = formset_factory(IngredientForm, extra=4)
    instructionFormSet = formset_factory(InstructionForm)

    if request.method == "POST":
        recipe = RecipeForm(request.POST)
        ingredients_forms = ingredientFormSet(request.POST, prefix="ingredient")
        instruction_forms = instructionFormSet(request.POST, prefix="instruction")

        if recipe.is_valid() and ingredients_forms.is_valid() and instruction_forms.is_valid():
            newRecipe = Recipe()
            newRecipe.title = recipe.cleaned_data['title']
            newRecipe.description = recipe.cleaned_data['description']
            newRecipe.save()

            for ingredient in ingredients_forms:
                cd = ingredient.cleaned_data
                ingredientName = cd.get('ingredient')
                try:
                    ingredientObj = Ingredient.objects.get(name=str(ingredientName))
                except Ingredient.DoesNotExist:
                    ingredientObj = Ingredient(name=str(ingredientName))
                finally:
                    ingAmount = IngredientAmount()
                    ingAmount.amount = cd.get('amount')
                    ingAmount.unit = cd.get('unit')

                    ingredientObj.save()

                    ingAmount.ingredient = ingredientObj
                    ingAmount.recipe = newRecipe
                    ingAmount.save()
                    newRecipe.ingredients.add(ingredientObj)
                    newRecipe.save()
            #used a counter because my initial way of doing this wont work
            i=1
            for instruction in instruction_forms:
                cd = instruction.cleaned_data
                instruct = cd.get('instruction')
                # I feel like the problem is somewhere in here
                instructObj = Instruction(instruction=instruct)
                instructObj.step = i
                instructObj.recipe = newRecipe
                instructObj.save()
                i+=1
else:
    ingredients_forms = ingredientFormSet(prefix="ingredient")
    instruction_forms = instructionFormSet(prefix="instruction")

return render(request, 'foods/createFood.html',{'recipeForm':recipeForm, 'ingredientFormSet': ingredients_forms, 'instructionFormSet': instruction_forms})

所以配料表和配方表可以正常工作,我可以添加配料并将它们全部添加到数据库中。但是,如果我添加一条指令,那么第一个指令会起作用,其他所有指令都不会返回None。

createFood.html

<div class="container" id="foodsPage">

    <form method="POST">
        {% csrf_token %}
        {{recipeForm.as_p}}

        {{ingredientFormSet.management_form}}
        {% for ingredient in ingredientFormSet %}
        <div class="fieldWrapper" id="ingForm0">
            {{ingredient.amount.label_tag}}
            {{ingredient.amount}}
            {{ingredient.unit.label_tag}}
            {{ingredient.unit}}
            {{ingredient.ingredient.label_tag}}
            {{ingredient.ingredient}}
        </div>
        {% endfor %}
        <div id="addMoreIng">
        </div>
            <input type="button" id="addIngredient" onclick="addIngFunction()" value="Add Ingredient">
        </div>


        <div class="instructions">
        <div id="addMoreIns">
         {{instructionFormSet.management_form}}
         {% for instruction in instructionFormSet %}
            {{instruction.step}}
            {{instruction.instruction.label_tag}}
            {{instruction.instruction}}
             </div>
              </div>
         {% endfor %}





         <input type="button" id="addInstruction" onclick="addInsFunction()" value="Add instruction">

         <script>

         function addIngFunction(){
            $('#id_ingredient-TOTAL_FORMS').val(function(i, oldval){
                    oldval
                    var html = '<div class="fieldWrapper" id="ingForm'+oldval+'">'+
            '<label for="id_ingredient-'+oldval+'-amount">Amount:</label>'+
            ' <input type="number" name="ingredient-'+oldval+'-amount" step="any" id="id_ingredient-'+oldval+'-amount" />'+
            ' <label for="id_ingredient-'+oldval+'-unit">Unit:</label>'+
            ' <input type="text" name="ingredient-'+oldval+'-unit" maxlength="3" id="id_form-'+oldval+'-unit" />'+
            ' <label for="id_ingredient-'+oldval+'-ingredient">Ingredient:</label>'+
            ' <input type="text" name="ingredient-'+oldval+'-ingredient" maxlength="100" id="id_ingredient-'+oldval+'-ingredient" />'+
        '</div>'


            $('#addMoreIng').append(html)
                    return ++oldval;
            })
        }

        function addInsFunction(){
            $('#id_instruction-TOTAL_FORMS').val(function(i, oldval){

                    var val = parseInt(oldval)+1
                    var html = '<input type="hidden" name="instruction-'+oldval+'-step" value="'+val+'" id="id_instruction-'+oldval+'-step" />'+
            '<label for="id_instruction-'+oldval+'-instruction">Instruction:</label>'+
            '<textarea name="instruction-'+oldval+'-instruction" cols="40" rows="10" id="id_instruction-'+oldval+'-instruction">'+
'</textarea>'

            $('#addMoreIns').append(html)
                    return ++oldval;
            })
        }
        </script>


        <input type="submit" value="submit recipe">


     </form>

</div>

我不知道为什么添加的任何指令都返回None。 有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您要关闭div中的两个{% for instruction in instructionFormSet %}  但应在循环外部将其关闭。我没有检查过,但是当浏览器将其解析到DOM中时,这可能会关闭比预期包含的form标记更多的标记。

这可能导致某些输入不再位于表单内(根据浏览器DOM),因此浏览器不会在POST请求中提交这些输入。尝试修复HTML。