django ManyToManyField保存

时间:2018-08-31 05:45:47

标签: django django-models django-forms django-views many-to-many

该表单包含许多字段(日期,字符,文本,图像,URL ...),它们工作正常。我的意思是,必须将值提交给DB。但是,当我添加ManyToManyField时,并没有将此MultipleChoice表单的值保存到DB。有什么想法吗?

models.py:

class EventTag(models.Model):
    tags = models.CharField(max_length=300)

    def __str__(self):
        return self.tags

class Article(models.Model):
    source = models.CharField(max_length=100)
    source_img = models.ImageField(default='default.png', blank=True)
    #other fields
    event_tags = models.ManyToManyField(EventTag, blank=True)

forms.py:

class CreateArticle(forms.ModelForm):
    class Meta:
        model = models.Article
        fields = ['source', 'source_img', 'event_tags', ]

views.py:

def article_create(request):
    if request.method == 'POST':
        form = forms.CreateArticle(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            return redirect('articles:list')
    else:
        form = forms.CreateArticle()
    return render(request, 'articles/article_create.html', { 'form': form })

1 个答案:

答案 0 :(得分:0)

保存表单后,必须调用form.save_m2m()。您的视图必须是这样的:

def article_create(request):
    if request.method == 'POST':
        form = forms.CreateArticle(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            form.save_m2m()
            return redirect('articles:list')
    else:
        form = forms.CreateArticle()
    return render(request, 'articles/article_create.html', { 'form': form })