简体   繁体   English

基于类的视图中的表单处理

[英]Form handling in class based view

I have problem when form is not valid (in POST method). 表单无效时(在POST方法中),我遇到问题。

didn't return an HttpResponse object. 没有返回HttpResponse对象。 It returned None instead. 它返回None。

I could paste this line to last line of Post method 我可以将此行粘贴到Post方法的最后一行

return render(request, self.template_name, context)

But context variable is initialized in Get method. 但是上下文变量在Get方法中初始化。 How can I pass context to post method? 如何将上下文传递给post方法?

class EventPage(View):
    template_name = 'event.html'

    def get(self, request, event_id):
        event = Event.objects.get(id = event_id)
        participants = Participant.objects.filter(event_id = event.id)
        register_to_event_form = RegisterToEvent()
        context = {
            'register_to_event_form': register_to_event_form,
            'title': event.title,
            'description': event.description,
        }
        return render(request, self.template_name, context)

    def post(self, request, event_id):
        event = Event.objects.get(id = event_id)
        if request.method == "POST":
            register_to_event_form = RegisterToEvent(request.POST)
            if register_to_event_form.is_valid():
                participant = register_to_event_form.save(commit=False)
                participant.event = event
                participant.save()
                return HttpResponseRedirect('/event-%s' %event_id)

You should not be doing things this way at all. 您根本不应该以这种方式做事。 The whole point of the class-based views is that they provide a series of methods for you to override which are called by the default implementations of get and post ; 基于类的视图的全部要点是,它们提供了一系列方法供您覆盖,这些方法由getpost的默认实现调用; you should not really be overriding get and post yourself. 您不应该真正压倒获取和发布自己的信息。

In your case you should be using a CreateView, not a plain view. 在您的情况下,您应该使用CreateView而不是普通视图。 And you should be returning the events and participants in a get_context_data method. 并且您应该在get_context_data方法中返回事件和参与者。 Setting the event property of the saved object should happen in the form_valid method. 设置保存对象的event属性应在form_valid方法中进行。

我认为在返回HttpResponseRedirect的格式无效的情况下,您需要else语句

you are not returning anything if your form is invalid, so you can do like: 如果表单无效,则不返回任何内容,因此您可以执行以下操作:

 def post(self, request, event_id):
    event = Event.objects.get(id = event_id)
    register_to_event_form = RegisterToEvent(request.POST)
    if register_to_event_form.is_valid():
        . . .      
        return HttpResponseRedirect('/event-%s' %event_id)
    else:
        context = {'register_to_event_form': register_to_event_form}
        return render(request, self.template_name, context)

and you dont need if request.method == "POST": in your post method 并且您不需要post。方法中的if request.method == "POST":

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

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