我创建了一个简单的页面,我可以添加文章(标题,文本和类别)。当我在“网站管理”上做的一切都很好,但是当我在页面上添加它时,我无法选择类别。
http://i.stack.imgur.com/4Nxzb.jpg
我选择类别,例如在此屏幕上,但我保存后文章没有此类别(文章未分类)。
我创建了forms.py文件,我这样做了:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text', 'categories')
我如何更改'类别'以使其可用?
models.py:
from django.db import models
from django.utils import timezone
class Category(models.Model):
name = models.CharField('Nazwa Kategorii', max_length=100)
slug = models.SlugField('Odnośnik', max_length=100)
icon = models.ImageField('Ikonka Kategorii', upload_to='icons',
blank=True)
class Meta:
verbose_name = "Kategoria"
verbose_name_plural = "Kategorie"
def __unicode__(self):
return self.name
class Post(models.Model):
author = models.CharField(max_length=25, blank=True, null=True)
title = models.CharField(max_length=200)
slug = models.SlugField('Odnośnik', max_length=255)
text = models.TextField()
published_date = models.DateTimeField(
default=timezone.now)
categories = models.ManyToManyField(Category, verbose_name='Kategorie')
def publish(self):
self.published_date = timezone.now()
self.save()
def __unicode__(self):
return self.title
来自views.py我的观点
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('blog.views.post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
答案 0 :(得分:0)
使用commit=False
保存表单时,您应该调用表单的save_m2m()
方法:
post = form.save(commit=False)
post.author = request.user
post.save()
form.save_m2m()
另一个更优雅的解决方案是将带有预设字段的instance
传递给表单的构造函数。在这种情况下,您不需要使用commit=False
参数:
form = PostForm(request.POST, instance=Post(author=request.user))
if form.is_valid():
post = form.save()
return redirect('blog.views.post_detail', pk=post.pk)