本文介绍了Django CreateView没有保存对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基本的博客应用程序练习django基于类的视图。
但是由于某种原因,我的Post模型的CreateView并未将帖子保存在数据库中。

I'm practicing django Class-Based-View with a basic blog application.For some reason, however, the CreateView for my Post model is not saving the post inside the database.

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')

forms.py

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        exclude = ('user', 'post_date')

views.py

class PostCreate(CreateView):
    template_name = 'app_blog/post_save_form.html'
    model = Post
    form_class = PostForm

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

显示的内容不包含产生任何错误,但是当我检查管理页面时,
由CreateView创建的帖子未保存在数据库中。.
任何想法.. ??

It displays content without generating any error, but when I check the admin page,the post created by the CreateView is not saved in the database..Any idea..??

谢谢

推荐答案

提示:请勿使用 exclude 在定义表单时,请使用 fields ,这是更安全的方法,也是推荐的做法。

One tip: don't use exclude when defining forms, use fields, is more secure and the recommended way to do it.

重定向是通过 get_success_url 方法定义的。如果您的模型中有方法 get_absolute_url CreateView 将重定向到该URL,否则您始终可以覆盖 get_success_url

The redirect is defined by get_success_url method. If you have in your model the method get_absolute_url CreateView will redirect to that URL, otherwise you can always override get_success_url in your view.

使用 get_absolute_url

Using get_absolute_url:

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')

    @permalink
    def get_absolute_url(self):
        return ('myurlname', (), {'myparam': something_useful})

使用 get_success_url

Using get_success_url:

class PostCreate(CreateView):
    template_name = 'app_blog/post_save_form.html'
    model = Post
    form_class = PostForm

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

    def get_success_url(self):
        return reverse('myurlname', args=(somethinguseful,))

我认为您在使用CBV时会发现此页面非常有用:

I think you will find this page very useful when working with CBVs:http://ccbv.co.uk/projects/Django/1.5/django.views.generic.edit/CreateView/

这篇关于Django CreateView没有保存对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 10:36