Guide to Sharing Django Recipes: Creating the ‘Add Meal’ Template (Tutorial 23)

Posted by

Django Recipe Sharing Tutorial – 23. The Add Meal Template

Django Recipe Sharing Tutorial – 23. The Add Meal Template

In this tutorial, we will learn how to create the Add Meal template for our Django Recipe Sharing web application.

Step 1: Create the Add Meal Template

First, let’s create a new HTML file called add_meal.html in the templates directory of our project. We can use the following code as a starting point:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Meal</title>
</head>
<body>
<h1>Add a Meal</h1>

<form action="" method="post">
{% csrf_token %}
<label for="name">Name:</label>
<input type="text" id="name" name="name">

<label for="description">Description:</label>
<textarea id="description" name="description"></textarea>

<input type="submit" value="Add Meal">
</form>
</body>
</html>

Step 2: Update the Views

Next, we need to update the views.py file in our project to handle the form submission from the Add Meal template. We can use the following code as a starting point:


def add_meal(request):
if request.method == 'POST':
form = MealForm(request.POST)
if form.is_valid():
form.save()
return redirect('meal_list')
else:
form = MealForm()
return render(request, 'add_meal.html', {'form': form})

With these changes, our Django Recipe Sharing web application now has a functioning Add Meal template and view. Users can use the form to add new meals to the database, and the views.py file handles the form submission and redirects the user to the meal list view after a meal has been added.

Conclusion

In this tutorial, we learned how to create the Add Meal template for our Django Recipe Sharing web application. By following these steps, we now have a fully functional form for adding new meals to our database.