简体   繁体   English

如何在Django CreateView和UpdateView中呈现Form实例?

[英]How to render Form instance in Django CreateView & UpdateView?

I'm trying to refactor my code into class-based views, and I'm having trouble understanding how to return/render at the end. 我试图将我的代码重构为基于类的视图,并且在理解最后如何返回/渲染时遇到麻烦。 I'm trying to render the form with the supplied POST data on success (or fail), with an appropriate confirmation message, so that it can be updated. 我正在尝试使用成功(或失败)时提供的POST数据以及适当的确认消息来呈现表单,以便可以对其进行更新。 Here's some example code, with comments showing what I want to return (where I don't know how): 这是一些示例代码,其中的注释显示了我想返回的内容(我不知道如何返回):

from django.views.generic import CreateView, UpdateView
from my_app.forms import ProductCreateForm
from my_app.models import Product
from django.contrib.auth.models import User

class ProductCreate(CreateView):
    """Simple CreateView to create a Product with ForeignKey relation to User"""
    model = Product
    form_class = ProductCreateForm
    template = 'product_create.html'

    def form_valid(self, form):
        user = User.objects.filter(username=form.cleaned_data['user_email']).first()
        if user is None:
            messages.error("Invalid user email specified")
            return some http response here...
            #How to I render the page again, but with the data already in the 
            #form we don't have to re-enter it all?
        form.save()
        messages.info("Successfully saved the product!")
        return some http response here...
        #How do I redirect to the UpdateView here with the Product instance 
        #already in the form?

class ProductUpdate(UpdateView):
    model = Product
    form_class = ProductCreateForm
    template = 'product_create.html'

You shouldn't be doing any of that there. 您不应该在那里做任何事情。 The view is already taking care of calling the validation methods and redisplaying the form if validation fails; 该视图已经负责调用验证方法并在验证失败时重新显示表单。 form_valid is only called if the form is already valid. 仅当表单已经有效时才调用form_valid Your user check should go into the form itself: 您的用户检查应进入表格本身:

class ProductCreateForm(forms.ModelForm):
    ...
    def clean_user_email(self):
        user = User.objects.filter(username=self.cleaned_data['user_email']).first()
        if user is None:
            raise forms.ValidationError("Invalid user email specified")
        return user

For the second part, redirecting to the update view, you can do that by defining the get_success_url method; 对于第二部分,重定向到更新视图,可以通过定义get_success_url方法来完成; what it returns depends on the URL you have defined for the ProductUpdate view, but assuming that URL takes an id argument it would be something like this: 返回的内容取决于您为ProductUpdate视图定义的URL,但是假设该URL带有id参数,则将是这样的:

class ProductCreate(CreateView):
    def get_success_url(self):
        return reverse('product_update', kwargs={'id': self.instance.pk})

That leaves your form_valid method only needing to set the message on success, and you don't even need to do that if you use the SuccessMessageMixin from contrib.messages. 这样一来,您的form_valid方法仅需要在成功时设置消息,如果您使用contrib.messages中的SuccessMessageMixin ,则甚至不需要这样做。

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

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