Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django forms: reload view after post

Tags:

forms

django

view

I have the following view code:

def activate( request = '', actkey = "" ):
    message = ""
    if len( actkey ) != 40:
        message += str( len(actkey))
        if request.method == 'POST':
            form = ActivateForm( request.POST )
            if form.is_valid():
                actkey = request.POST['actkey']
                activate( '', actkey )
        else:
            form = ActivateForm()
    else:
        profile = userprofile.objects.get( actkey = actkey )
        user = User.objects.get( id = profile.user_id )
        user.is_active = True
        user.save()
        profile.actkey = ""
        profile.save()
        message += "Uw account is succesvol geactiveerd."
        return render_to_response( 'profile/register.html', { 'message' : message } )
    return render_to_response( 'profile/register.html', { 'message' : message, 'form' : form } )

What it does is simple, when the activation key is given through the URL, it goes to: profile = userprofile.... etc. But when it's not given it loads the django form so the user can type it's activation code (all works well so far) But when the user posts his activation key it comes in the if len( actkey ) != 40: That shouldn't happen because the activation key is 40... But since it shows the form again, but activates the user as well i get unwanted behavior...

How can i fix this?

Thanks for the help

like image 562
Bloeper Avatar asked Sep 30 '25 09:09

Bloeper


1 Answers

You should redirect after a successful form submission

 if request.method == 'POST':
   form = ActivateForm( request.POST )
   if form.is_valid():
     actkey = form.cleaned_data['actkey']#access cleaned_data instead of raw post
     activate( '', actkey )
     return HttpResponseRedirect('/')
like image 57
czarchaic Avatar answered Oct 02 '25 05:10

czarchaic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!