I have created a page for review form. All users can fill out the form, but only logged in users can submit the form. If users is not logged in, they will be redirected to the login page. After they login, they will be redirected to the profile page.
So the flow will be like this : User fills out the form > click the submit > redirected to login page > user login and redirected to profile page (at the same time, the form they have filled in is automatically saved)
I want the form they have filled in automatically saved after they login. How to do that?
My idea is to create a session that saves the form temporarily, then save to database after they login. But I'm confused how to write the code
Can anyone explain a bit what a django session is like? and how to write code to handle this problem?
CodePudding user response:
You can try something like,
1 User fills out the form and hits submit
2 in the POST view where you handle the form, use the "**is_authenticated**" function and,
a)if the user is authenticated you handle the form as usual...
b)else set the contents of the form into a session variable in the views and redirect to the login page like,
request.session['review_body'] = request.post.get(the_form_body_field)
3 as per what you've said, after login it goes to profile page and form is submitted...
a)so in views where you serve the profile page, check if the session variable containing form data's exist and has values
b)if yes, directly save the contents from your views and clear the session data
CodePudding user response:
I've used a similar way which you can implement,
so in your views add the following code that fits your criteria
@login_required
def myform(request):
if request.method == 'GET':
return render(request, 'appname/myform.html', {'form':appnameForm()})
else:
try:
form = appnameform(request.POST)
newform= form.save(commit=False)
newform.user = request.user
newform.save()
return redirect('Home')
except ValueError:
return render(request, 'todo/myform.html', {'form':appnameform(), 'error':'Bad data passed in,Try again'})
also import on views the following:
from django.contrib.auth.decorators import login_required
and in your setting don't forget to add
LOGIN_URL = '/login'
If you want to learn django a bit more i suggest Zappycode.com Nick Walter has great Django courses where he cover this
Here is the source Code for the project that covers this and here is the video tutorial