How to process a form (via get or post) using class-based views?

前端 未结 2 1304
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 01:26

Im trying to learn class-based views, for a detail or list view is not that complicated.

I have a search form and I just want to see if I send a query to show up the res

2条回答
  •  孤街浪徒
    2021-01-30 01:46

    The default behaviour of the FormView class is to display an unbound form for GET requests, and bind the form for POST (or PUT) requests. If the bound form is valid, then the form_valid method is called, which simply redirects to the success url (defined by the success_url attribute or the get_success_url method.

    This matches the example quite well. You need to override the form_valid method to create the new User, before calling the superclass method to redirect to the success url.

    class CreateUser(FormView):
        template_name = 'registration/register.html'
        success_url = '/accounts/register/success/'
        form_class = RegistrationForm
    
        def form_valid(self, form):
            user = User.objects.create_user(
                    username=form.cleaned_data['username'],
                    password=form.cleaned_data['password1'],
                    email=form.cleaned_data['email']
            )
            return super(CreateUser, self).form_valid(form)
    

    Your first example does not match the flow of FormView so well, because you aren't processing a form with POST data, and you don't do anything when the form is valid.

    I might try extending TemplateView, and putting all the logic in get_context_data. Once you get that working, you could factor the code that parses the GET data and returns the bookmarks into its own method. You could look at extending ListView, but I don't think there's any real advantage unless you want to paginate results.

提交回复
热议问题