How to add multiple categories to a model using a form in Django?
I have a model called BlogPost and one called Category, each BlogPost can have multiple categories. When creating posts from the admin panel I have no problems, but when trying to implement a form that creates a BlogPost so users can create posts I get an error:
Direct assignment to the forward side of a many-to-many set is prohibited. Use categories.set() instead.
I tried reading the documentation but there's something that I'm not understanding because it's not working.
My models are this;
class BlogPost(models.Model):
title = models.CharField(max_length=250)
content = models.TextField()
post_author = models.CharField(max_length=30)
creation_date = models.DateTimeField(auto_now_add=True)
modification_date = models.DateTimeField(auto_now=True)
image = models.ImageField(upload_to='blog/files/blog_images')
categories = models.ManyToManyField('Category', related_name='posts') #Relaciona el atributo con la clase Category y permite usar category.posts
def __str__(self):
return self.title
class Meta:
verbose_name = "blog post"
verbose_name_plural = "blog posts"
class Category(models.Model):
cat_name = models.CharField(max_length=50)
def __str__(self):
return self.cat_name
class Meta:
verbose_name = "category"
verbose_name_plural = "categories"
This is the form:
class newPostForm(forms.Form):
CATEGORIES = (
(1, "Agua dulce"),
(2, "Agua marina"),
(3, "Primer acuario"),
(4, "Alimentación")
)
título = forms.CharField(max_length=250)
contenido = forms.CharField(
widget=forms.Textarea()
)
imagen = forms.ImageField()
autor = forms.CharField()
categorias = forms.ModelMultipleChoiceField(
queryset=Category.objects.all(),
widget=forms.CheckboxSelectMultiple
)
And this is the view:
def new_post(request):
if request.method == "POST":
form = newPostForm(request.POST, request.FILES)
if form.is_valid():
info = form.cleaned_data
new_post_info = BlogPost(
title=info["título"],
content=info["contenido"],
image=info["imagen"],
post_author=info["autor"],
categories=info["categorias"]
)
new_post_info.save()
return redirect(request.path_info)
else:
form = newPostForm()
return render(request, "blog/new_post.html", {"form":form})
Any suggestion is welcomed!
I tried with the saving before and adding the categories as described in the documentation but it didn't work.
I solved it, this is how for anyone wondering:
Modified the view to:
def new_post(request):
if request.method == "POST":
form = newPostForm(request.POST, request.FILES)
if form.is_valid():
info = form.cleaned_data
new_post_info = BlogPost(
title=info["título"],
content=info["contenido"],
image=info["imagen"],
post_author=info["autor"],
)
new_post_info.save()
new_post_info.categories.set(info["categorias"])
return redirect(request.path_info)
else:
form = newPostForm()
return render(request, "blog/new_post.html", {"form":form})
It now takes what is stored into the "categorias" field form the form and passes it to the BlogPost object attribute categories after saving the new_post_info object.
PD: I don't know if it's customary for one to answer their own question, but this may help someone in the future.