S
S
Sergey Nizhny Novgorod2016-06-24 19:54:55
Django
Sergey Nizhny Novgorod, 2016-06-24 19:54:55

How to properly validate forms in Django?

Situation:
1) There is a view that uploads the data of the desired user to the card and creates a forum for filling 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'], #убрали в самом конец .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 processes the data filling form.
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' = "Ошибка"
                return redirect('/profile'+ add_id, token, error)

And the problem is that if the validation of the second view is violated, I cannot pass the information by mistake to 1 view so that the {{ error }} error is drawn.
_________
i.e. I don't understand how to link validation from one view to the second if the first view generates the form and the second view processes it. Since from the second view it is impossible to transfer any information to the first.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question