Home > database >  Model Forms not saving ManytoMany Field
Model Forms not saving ManytoMany Field

Time:10-02

here is my code. I am using Modelforms and Crispy forms library to generate form. when I click form submit everything is saved, except Category(manytomanyfield), that I have to specify manually from admin panel.

NOTE: I FOUND SOME SOLUTIONS ONLINE to do form.save_m2m() but I get Object has no attribute save_m2m()

my modelform.

from django.forms import ModelForm
from .models import Article


class ArticleForm (ModelForm):
  class Meta:
    model = Article
    fields = '__all__'
    exclude = ('user',)

my views.

def create(request):

if request.method =="POST":
    form = ArticleForm(request.POST, request.FILES)
    if form.is_valid():
        form = form.save(commit=False)
        form.user = request.user
        
        return redirect('home')

form = ArticleForm()
context = {'form': form}

return render(request, 'article_form.html', context)

my template.

<form action="" enctype="multipart/form-data" method="post">
            {% csrf_token %}
            {{form|crispy}}
            <button type="submit" >Submit</button>
        </form>

CodePudding user response:

You're overwriting form:

The code should be:

if form.is_valid():
    #form.save() returns a model instance, not another form
    article = form.save(commit=False) 
    article.user = request.user
    article.save()
    form.save_m2m()
...
  • Related