Django的CreateView没有保存对象

时间:2013-07-24 11:47:20

标签: python django

我正在练习Django的通用视图,尤其是ModelForms

这些是我的观点和模型

models.py

class Post(models.Model):
    user = models.ForeignKey(User)
    post_title = models.CharField(max_length=200)
    post_content = models.CharField(max_length=500)
    post_date = models.DateTimeField('date posted')

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

    def __unicode__(self):
        return self.post_title

forms.py

class PostForm(forms.ModelForm):
    post_title = forms.CharField(
        label=u'Title',
        widget=forms.TextInput(attrs={'size':64})
    )
    post_content = forms.CharField(
        label=u'Content',
        widget=forms.TextInput(attrs={'size':128})
    )
    class Meta:
        model = Post

views.py

class PostCreate(CreateView):
    fields = ['post_title', 'post_content']
    template_name = 'app_blog/post_save_form.html'
    model = Post
    form_class = PostForm   

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(PostCreate, self).dispatch(*args, **kwargs)

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.post_date = datetime.now()
        return super(PostCreate, self).form_valid(form)

视图似乎工作正常,没有显示任何错误。但是,当我在提交表单并保存帖子后检查Django管理页面时,由于某种原因,帖子不会保存到数据库中。

知道为什么会这样吗?

2 个答案:

答案 0 :(得分:5)

正如我从您的代码中看到的那样,您可以使用

self.object = form.save(commit=False)

表示该对象不会保存到数据库中,但您可以将其用于进一步处理。所以你应该使用这样的东西:

self.object = form.save(commit=False)  # Not hit database
self.object.user = self.request.user  # Update user
self.object.post_date = datetime.now()  # Update post_date
self.object.save()  # And finally save your object to database.

答案 1 :(得分:1)

试试这个。

def form_valid(self, form):
    form.instance.user = self.request.user
    form.instance.post_date = datetime.now()
    return super(PostCreate, self).form_valid(form)