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
?
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:
....