[Answered ]-Django "if request.method == 'POST':" returns False

1πŸ‘

It is necessary to return HttpResponseRedirect after dealing with POST data, the tip is not specific to Django, it’s a good web practice in general.

Also, try to maintain both GET and POST request separately, so try below view:

def recipe_create_view(request):
    context = {}
    form="" # for the error of variable refrenced before assignment.
    IngredientFormset=""
    formset=""

    if request.method == 'POST':
        form = RecipeForm(request.POST)
        IngredientFormset = formset_factory(IngredientForm)
        formset = IngredientFormset(request.POST)

        if form.is_valid():
            if formset.is_valid():
                form.save()
                print("made a recipe")
                
                for form in formset:
                    child = form.save(commit=False)
                    child.recipe = parent
                    child.save()
                    print("made a Ingredient")
                return redirect('some_success_path_name')
   
            else:
                print("formset is not valid")
        else:
            print("form is not valid")
    else: # GET method
        print("request method is GET")
        form = RecipeForm()
        IngredientFormset = formset_factory(IngredientForm)
        formset = IngredientFormset()
        context['form'] = form
        context['formset']  = formset

        

    return render(request, 'recipes/create_recipe.html', context)

0πŸ‘

add action in your HTML form and POST in small case.

<form action="/your_backend_url_to_view/" method="post">
    {% csrf_token %}
    <label>recipe</label>
    <p>{{form}}</p>


    <label>ingredients</label>
    {% for form in formset %}
        
        <ul>
            <label>name</label>
            <li>{{ form.name }}</li>
            <label>quantity</label>
            <li>{{ form.quantity }}</li>
        </ul>
    {% endfor %}
    <div>
        <input type="submit" value="submit" class="button-33" role="button">
    </div>
</form>
πŸ‘€shivankgtm

Leave a comment