Execute these steps to complete the recipe:
- Create the forms.py file and put a simple model form there:
# quotes/forms.py from django import forms
from .models import InspirationalQuote
class InspirationalQuoteForm(forms.ModelForm):
class Meta:
model = InspirationalQuote
fields = ["author", "quote", "picture", "language"]
- In the views.py file, put a view that handles the form. Don't forget to pass the FILES dictionary-like object to the form. When the form is valid, trigger the save method as follows:
# quotes/views.py from django.shortcuts import render, redirect
from .forms import InspirationalQuoteForm
def add_quote(request):
form = InspirationalQuoteForm()
if request.method == "POST":
form = InspirationalQuoteForm(
data=request.POST,
files=request.FILES)
if form.is_valid():
form.save()
return redirect("quotes-list")
else:
return render(request, "quotes/add_quote.html", {
"form": form
})
- Add a rule in urls.py for the add form:
# quotes/urls.py
from django.urls import path
from .views import add_quote
urlpatterns = [
path('add/', add_quote, name='quote_add'),
]
- We also need to include the quotes app URLs in our project:
# project/urls.py
from django.urls import include, path
urlpatterns = [
# ...
path('quotes/', include('quotes.urls')),
]
- Create a template for the view in templates/quotes/add_quote.html. It is very important to set the enctype attribute to multipart/form-data for the HTML form, otherwise the file upload won't work:
{# templates/quotes/add_quote.html #}
{% load i18n %}
{% block content %}
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">{% trans "Save" %}</button>
</form>
{% endblock %}