Django: ListView with post() method?

僤鯓⒐⒋嵵緔 提交于 2019-12-03 14:17:10
# Django is complaining that status_form does not exist,
# result since the post method is not executed
context['status_form'] = self.status_form

Because you didn't define self.status_from in the first place. You have defined it in get_context_data, and it's accessible from there.

You can access you object from get_context_data in your post method;

context = self.get_context_data(**kwargs)
status_form = context['status_form']

Also consider that you can define your status_form directly in post method itself without getting it from self or get_context_data.

Redesign you views to separate each Form processing in separate Views then tight them with each-other.

Views redesign:

In nutshell, let each view to do one job. You can create a View just for processing your status_form and name it like StatusFormProcessView then on your List view return it on its post method

class List(ListView);
    def post(self, request, *args, **kwargs):
        return StatusFormView.as_view()(request) # What ever you need be pass to you form processing view

This is just an example of it, need more work to be real.

For another example; On my website index page I have a search form. when user POST or GET the search form, The processing of searching doesn't exist in my IndexView, instead I handle the whole form stuff in separate view, If form should process on GET method, I'll override get() method, If form should process on POST, I'll override post() method to send search_form data to the view that is responsible for handling of processing the search_form.

Comments response

status_form = context['status_form']

shouldn't it be

context['status_form'] = status_form

after I created it ?

You want to get status_form from context, So you need to

status_form = context['status_form']

Anyway, your form data are available on self.request.POST

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!