How to validate forms in Django?

Situation:

1) There is a view that uploads the desired user to the card and creates a forum to fill in additional fields.

def profile(request, profile_id):
 useritem = User.objects.get(id = profile_id) 
 form = Profile_Form(request.POST)

 if request.user.is_authenticated():
 current_user = request.user
 if str(current_user.id) == str(useritem.id): 
 profileinfo = {
 # 'avatar' : get_thumbnailer(useritem.profile.avatar)['avatar'], #removed in the end .url
 'avatar' : useritem.profile.avatar
 'myself' : useritem.profile.myself,
 'myoffer' : useritem.profile.myoffer,
 'get_status' : useritem.profile.get_status,
 'get_plus' : useritem.profile.get_plus,
 "editable" : True, 

 context = {
 "useritem" : useritem,
 "profileinfo" : profileinfo,
 "form" : form, 
}
 return render(request, 'faceset/profile.html', context)


2) There is a view that handles the form data.

def update_profile(request, add_id):
 token = {}
token.update(csrf(request))
 if request.user.is_authenticated():
 current_user = request.user

 useritem = User.objects.get(id = current_user.id) 

 if request.POST:
 form = Profile_Form(request.POST)
 if form.is_valid(): 
 myself = form.cleaned_data['myself']
 myoffer = form.cleaned_data['myoffer']
 profile_obj = Profile(user=current_user, myself=myself, myoffer = myoffer)
profile_obj.save()
 return redirect('/profile'+ add_id, token)
else:
 'error' = Error
 return redirect('/profile'+ add_id, token, error)


The problem is that in case of violation of the validation of the second view, I can't pass the information on mistake 1, a view to't render error {{ error }}.

_________

Ie, I don't know how to link the validation of one view second, if the first view generates a form, and second, the view handles it. As from the second view fails to transfer any information in the first.
July 8th 19 at 12:14
1 answer
July 8th 19 at 12:16
Solution
  1. Not usually divided into two views, and doing in one.
  2. For the model the form is made of ModelForm
  3. Why is the token.update(csrf(request)), checking for csrf is used transparently
  4. Why pass add_id and profile_id, when the current user from the request
  5. if str(current_user.id) == str(useritem.id) is all trash, if you use the previous tip, this will not be reached
Could you clarify on the 3 point. How the code would look validate the token? - Shanie_Armstrong98 commented on July 8th 19 at 12:19
In the template with a form something like that:{% csrf_token %}, but this will do CsrfViewMiddleware middleware.if you have not deactivated it when configuring the project. And Yes, the same documentation:https://docs.djangoproject.com/en/1.9/ref/csrf/ - moriah.Stamm commented on July 8th 19 at 12:22

Find more questions by tags DjangoPython