Search code examples
pythondjangopostgetrequest

Django: POST and GET request and rendering on a template


I'm probably lost in a glass of water but at the moment I can't figure it out. I'm working on a restaurant capstone project where the client is able to see a menu page, a purchase page and the owner of the restaurant after login is able to manage and enter a new recipe and create his personal menu. What I'm trying to do is: when the owner of the restaurant submits a POST request where he entered the recipe, i want that the recipe appear also in the page where is the menu. In this way is able to update new recipe and change maybe the old one. (I copy model, form and view code for a complete overview):

form.py

class RecipeForm(forms.ModelForm):
class Meta:
    model = Recipe
    fields = '__all__'

model.py

class Recipe(models.Model):
name = models.CharField(max_length=50)
ingredients = models.CharField(max_length=500)

def __str__(self):
    return self.name

View.py

def recipeEntry(request):
recipe_menu = Recipe.objects.all()
form = RecipeForm()

if request.method == 'POST':
    form = RecipeForm(request.POST)
    if form.is_valid():
        form.save()

    return redirect("recipe")

context = {'form':form, 'recipe_menu':recipe_menu}
return render(request, 'inventory/recipe.html', context)

recipe.html

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Recipe</title>
</head>
<body>
    <form method="post", action="">{% csrf_token %}
        {{form.as_p}}
        <input type="submit" value="Add Recipe">
    </form>

    {% for rec in recipe_menu %}
    <div>
        <p>Recipe: {{rec.name}}</p>
        <p>Ingredient :{{rec.ingredients}}</p>

    </div>
    {% endfor %}
</body>
</html>

At the moment the part of submitting the POST request it works so is only the second part that don't works. I tried a bit few solution but i don't understand what to do. I thought also to create a GET view for the menu page but i need to pass an URL for get the data and i didn't works.

Thank you very much for the help.


Solution

  • You must try with explicitly instantiate empty form when it's not a post request :

    def recipeEntry(request):
        recipe_menu = Recipe.objects.all()
        # form = RecipeForm() Not here yet
    
        if request.method == 'POST':
            # Instantiate form with request.POST
            form = RecipeForm(request.POST)
            if form.is_valid():
                form.save()
            return redirect("recipe")
        else:  # Explicitly write else block
            # Instantiate empty form for get request
            form = RecipeForm()
    
            context = {'form':form, 'recipe_menu':recipe_menu}
            return render(request, 'inventory/recipe.html', context)