如何在Django中将对象实例填充到UpdateView表单中?

时间:2016-08-25 19:23:26

标签: python django

我有一个CreateView和UpdateView,并且在CreateView中成功后我试图返回UpdateView,其中已经填写了表单中的对象实例。下面的代码成功创建了对象实例(并根据代码重定向到其中带有uuid模式的url),但UpdateView表单为空。为什么?我该如何解决这个问题?

views.py

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)

urls.py

url(r'^create-product/$', ProductCreate.as_view(), name="productcreate"),
url(r'^update-product/(?P<uuid>#giant_uuid_regex#)/$', ProductUpdate.as_view(), name="productupdate"),

productcreate.html提取:

{{ form.as_p }}

forms.py(我遗漏了字段清理代码以及模型中没有的其他几个字段):

class ProductCreateForm(forms.ModelForm):
    """Form to support adding a new Product"""

    class Meta:
        model = Product
        fields = (
            'field1',
            'etc...',
        )

0 个答案:

没有答案