简体   繁体   English

Django CreateView 不保存对象

[英]Django CreateView is not saving object

I'm practicing django Class-Based-View with a basic blog application.我正在用一个基本的博客应用程序练习 django 基于类的视图。 For some reason, however, the CreateView for my Post model is not saving the post inside the database.但是,出于某种原因,我的 Post 模型的 CreateView 没有将帖子保存在数据库中。

models.py模型.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表格.py

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

views.py视图.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)

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..??它显示内容而不会产生任何错误,但是当我检查管理页面时,CreateView 创建的帖子没有保存在数据库中.. 任何想法..??

Thanks谢谢

One tip: don't use exclude when defining forms, use fields , is more secure and the recommended way to do it.一个提示:在定义表单时不要使用exclude ,使用fields更安全,也是推荐的方法。

The redirect is defined by get_success_url method.重定向由get_success_url方法定义。 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 CreateView方法将重定向到该 URL,否则您始终可以在您的视图中覆盖get_success_url

Using get_absolute_url :使用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})

Using get_success_url :使用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,))

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/我认为在使用 CBV 时,您会发现此页面非常有用: http : //ccbv.co.uk/projects/Django/1.5/django.views.generic.edit/CreateView/

the problem is that you are excluding fields that are mandatory, so it won't pass through your form validation.问题是您排除了必填字段,因此它不会通过您的表单验证。

You should pass this fields hidden with some default value, let the use fill them, set them to null=True or populate them before you access form_valid您应该使用一些默认值隐藏这些字段,让使用填充它们,将它们设置为 null=True 或在访问 form_valid 之前填充它们

I think this is a simple case of not calling form.save() .我认为这是一个不调用form.save()的简单情况。 When the form is validated, all of the checks are done, but it doesn't actually save the object in the database.当表单被验证时,所有的检查都完成了,但它实际上并没有将对象保存在数据库中。 To do that, you explicitly need to tell it to, via the save() method.为此,您需要通过save()方法明确告诉它。

So you want:所以你想要:

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)

I came across this question today after many years but those answer seems not correctly.多年后我今天遇到了这个问题,但这些答案似乎不正确。

The main issue here is the form.instance is None for CreateView.这里的主要问题是 CreateView 的 form.instance 是 None 。 So my approach is below as suggestion form django docs:所以我的方法如下作为 django 文档的建议表:

def form_valid(self, form):
    instance = form.save(commit=False)
    instance.user = self.request.user
    instance.post_date = datetime.now()
    instance.save()
    return redirect(self.get_success_url())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM