0

I am building a page for user registration. I want the customer to enter information step by step, so I want to separate the forms. For example, entering username, password, then go to next page and enter other information. I realize that with session. here is the code snipet

class RegisterBaseView(CreateView):
    def form_valid(self, form):
        for name in form.register_fields:
            self.request.session.update(
                {
                    name: form.cleaned_data[name]
                 }
            )

        return HttpResponseRedirect(self.success_url)



class RegisterProfileView(RegisterBaseView):
    form_class = RegisterProfileForm
    success_url = reverse_lazy('')
    template_name = 'player/register_profile.html'

class RegisterUserView(RegisterBaseView):
    form_class = RegisterUserForm
    success_url = reverse_lazy('')
    template_name = 'player/register_user.html'

I want RegisterUserView redirect to RegisterProfileView directly without urls.py, because I save the object finally linking to each other.

How should I write success_url ?

q2ven
  • 187
  • 9

1 Answers1

3

You can't redirect to another view without the url. You are updating the request.session in each view. You can access the data from session using session.get() method. If you don't write/call a save method within the view or form, then it shouldn't save anything. In final view of the chained views, you can save the data like this:

class FinalView(CreateView):

    def form_valid(self, form):
       name = self.request.session.get('name', None)
       ....
       if form.is_valid():
           data = form.cleaned_data['data']
           your_model = YourModel()
           your_model.name = name
           your_model.data = data
           your_model.save()

To prevent users accessing any middle view, do like this:

class MiddleView(SomeView):

    def form_valid(self):
        if self.request.session.get('name', None) is None:
            return HttpResponseRedirect('/first_view_url')
        else:
          ....
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • Thank you, then how should I prevent from accessing the chained middle view by entering the url directly? – q2ven Apr 28 '16 at 05:43
  • you can put it directly or put it by using `success_url`. Another thing, you need to put separate url associated with each view. – ruddra Apr 28 '16 at 05:47
  • Is it impossible that if user directly accesses the middle view, the view blocks the user and redirects to the first chained view? – q2ven Apr 28 '16 at 05:55
  • 1
    Thank you ruddra, I'll thumb up! – q2ven Apr 28 '16 at 06:03