如何在CreateView中获取创建的对象 [英] How to get created object in CreateView

查看:68
本文介绍了如何在CreateView中获取创建的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我使用CreateView创建项目,然后重定向用户以更新当前创建的对象的其他字段。

Here I am using CreateView to create item and after that i am redirecting user to update other fields of currently created object.

这里是我的代码:

Views.py

class DynamicCreate(CreateView):
    model = Dynamic
    form_class = DynamicForm
    template_name = 'book/dynamic_create.html'

    def form_valid(self, form):
        book = form.save(commit=False)
        book.user = User.objects.get(pk=(self.request.user.pk))
        book.save()
        return reverse('book:dynamicupdate', args=(self.object.id))


Urls.py

url(r'^book/create/$', views.DynamicCreate.as_view(), name='dynamiccreate'),
url(r'^book/delete/(?P<pk>[\w]+)/$', views.DynamicDelete.as_view(), name='dynamicdelete'),
url(r'^book/update/(?P<pk>[\w]+)/$', views.DynamicUpdate.as_view(), name='dynamicupdate'),

但是在这里我得到了错误:

But Here I am getting error:

Exception Type:     AttributeError
Exception Value:    'NoneType' object has no attribute 'id'

我遇到了其他先前问过的问题,例如 ,但是我不知道我在这里想念的是什么。我的CreateView可以在Table中创建/保存数据,但不能重定向我以更新View页面。

I go through other previously asked question like This, But I don't know What I am missing here. My CreateView is able to create/save data in Table but it is not able to redirect me to update View Page.

推荐答案

从ModelFormMixin继承的form_valid方法包含将self.object设置为新创建的对象的逻辑,但是您的替代方法使用book变量代替。如上所述,将args更改为参考书即可。

The form_valid method inherited from ModelFormMixin includes logic to set self.object to the newly created object, but your overriding method uses the book variable instead. Changing the args to reference book as mentioned above works fine.

另一种选择是,如果仅遵循由set设置的示例,则将book变量替换为self.object。默认方法。

Another option would be to replace the book variable with self.object, if only to follow the example set by the default method.

这篇关于如何在CreateView中获取创建的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆