Problems with forms from models

Hi !

I’m new to django, currently developing my first app, some kind of inventory for a library, and I’m struggling to do the adding form, to add a book in the inventory.
I’ve searched several ways to do that, and the one I prefer is from this documentation page (Model forms section) :
https://docs.djangoproject.com/en/3.1/topics/class-based-views/generic-editing/

It’s elegant, it suits my code, and it’s supposed to work well, with only a few lines of code, but I can’t make it work and I don’t understand why, it’s been 2 days. I hope it’s not a common error or some newbie one, sorry if it’s the case.

So here’s my code :

models.py :

class Livre(models.Model):
isbn = models.CharField(max_length=255, null=1)
titre = models.CharField(max_length=255)
editions = models.ManyToManyField('Edition')
auteurs = models.ManyToManyField('Auteur')
date_publication = models.DateField()
avis = models.CharField(max_length=500, null=1)
categories = models.ManyToManyField('Categorie')
themes = models.ManyToManyField('Theme')
empruntable = models.BooleanField()
emprunteur = models.CharField(max_length=255, null=1)
quantite_stock = models.IntegerField(null=1)
quantite_vendus = models.IntegerField(null=1)
prix = models.FloatField()
a_commander = models.BooleanField()
distributeur = models.CharField(max_length=255, null=1)

def __str__(self):
	return self.titre

def get_absolute_url(self):
	return reverse('livre', kwargs={'pk': self.pk})

views.py :

from django.shortcuts import get_list_or_404, get_list_or_404, render
from django.http import HttpResponse
from django.template import loader
from django.views import generic
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from django.forms import modelformset_factory
from django.urls import reverse_lazy

from .models import Livre, Auteur, Edition, Categorie, Theme

class CreateLivreView(generic.CreateView):
model = Livre
fields = ['isbn', 'titre', 'editions', 'auteurs', 'date_publication', 'avis', 'categories', 'themes', 'empruntable', 'emprunteur', 'quantite_stock', 'quantite_vendus', 'prix', 'a_commander', 'distributeur']
template_name = 'livreform.html'

urls.py :

from . import views

urlpatterns = [
    path('livre/add/', views.CreateLivreView.as_view(), name="add_livre"),
]

livreform.html :

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'add_livre' %}" method="post">
    {% csrf_token %}
    {{ formset }}
    <imput type="submit" value="Ajouter">
</form>

So there it is, I think I’ve done all I saw on the documentation, the result is blank, I don’t have the inputs nor even the submit button, the formset is emtpy :frowning: can you help me ?

From the CreateView docs, the example at the bottom, you can see in the “author_form.html” that you render an object named “form”, not “formset” using one of the form rendering methods.

Ken

1 Like

Okay, so it was that dumb… Sorry and thank you very much !