Python 如何在Django中将对象实例填充到UpdateView表单中?
我有一个CreateView和UpdateView,在CreateView中成功后,我尝试返回UpdateView,其中的对象实例已经填充在表单中。下面的代码成功创建了对象实例(并根据代码重定向到包含uuid模式的url),但UpdateView表单为空。为什么?我该如何解决这个问题 views.pyPython 如何在Django中将对象实例填充到UpdateView表单中?,python,django,Python,Django,我有一个CreateView和UpdateView,在CreateView中成功后,我尝试返回UpdateView,其中的对象实例已经填充在表单中。下面的代码成功创建了对象实例(并根据代码重定向到包含uuid模式的url),但UpdateView表单为空。为什么?我该如何解决这个问题 views.py class ProductCreate(CreateView): """Simple CreateView to create a Product.""" model = Prod
class ProductCreate(CreateView):
"""Simple CreateView to create a Product."""
model = Product
form_class = ProductCreateForm
template_name = 'productcreate.html'
def get_success_url(self):
kwargs = {'uuid': self.object.uuid}
return reverse_lazy('productupdate', kwargs=kwargs)
def form_valid(self, form):
#some fields depend on request.user, so we can't set them in the Form.save() method
product = form.save()
product.fk_user = self.request.user
product.save()
return super(ProductCreate, self).form_valid(form)
class ProductUpdate(UpdateView):
"""Simple UpdateView to update a Product"""
model = Product
form_class = ProductCreateForm #same form
template_name = 'productcreate.html' #same template
def get_object(self, **kwargs):
#get the uuid out of the url group and find the Product
return Product.objects.filter(uuid=kwargs.get('uuid')).first()
def get_success_url(self):
kwargs = {'uuid': self.object.uuid}
return reverse_lazy('productupdate', kwargs=kwargs)
url.py
url(r'^create-product/$', ProductCreate.as_view(), name="productcreate"),
url(r'^update-product/(?P<uuid>#giant_uuid_regex#)/$', ProductUpdate.as_view(), name="productupdate"),
py(我省略了字段清理代码和模型中没有的几个附加字段):
添加了forms.py。您调试过吗?你确定get_object()正在返回一个实例吗?Michael,你是对的
kwargs.get('uuid')
是None
。它需要是self.kwargs.get('uuid')。如果你把它贴出来作为答案,我会接受的。阿拉斯代尔,谢谢。在这个特定的UX案例中,对于POST数据,我更喜欢静默失败,只在UpdateView上显示一个空表单?你确定get_object()正在返回一个实例吗?Michael,你是对的kwargs.get('uuid')
是None
。它需要是self.kwargs.get('uuid')。如果你把它贴出来作为答案,我会接受的。阿拉斯代尔,谢谢。在这个特定的UX案例中,对于POST数据,我更喜欢静默失败,只在UpdateView上显示一个空表单。
{{ form.as_p }}
class ProductCreateForm(forms.ModelForm):
"""Form to support adding a new Product"""
class Meta:
model = Product
fields = (
'field1',
'etc...',
)