Creating a user signup and a django-user at the same time. Save method is adding user regardless of valid form

StackOverflow https://stackoverflow.com/questions/4070657

Question

I have a team registration app. A user signs up to be a part of the team. When they do so, the view adds a team member and adds the user into the auth db.

However, when the team model returns invalid data, the user.save() method is adding the username, password and email.

So, when a user corrects the team registration, and clicks submit, they are now told that the username is taken.

What I want to have happen is the username etc is added AFTER the teammember has been validated.

Any suggestions?

Here's the view:

def register(request, **kwargs):
    if request.method == 'POST':
        form = SimpleRegForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            password = form.cleaned_data['password1']
            user = User.objects.create_user(username, email, password)
            user.save()
            form.save()

            # Send an email to the admin letting them know that a person registered
            subject = render_to_string('teamregistration/email_subject.txt')
            message = render_to_string('teamregistration/email_body.txt',
                                       {'first_name':form.cleaned_data['first_name'], 'last_name':form.cleaned_data['last_name'], 'tbi_region':form.cleaned_data['tbi_region']})
            recipients = ['XXXXXX@XXXXXX.XXX', 'XXXXXX@XXXXXX.XXX']
            send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipients)

            return HttpResponseRedirect('/tbi-team-register/registration-submitted/')
    else:
        form = SimpleRegForm()

    return render_to_response('teamregistration/form.html', {'form':form}, context_instance=RequestContext(request))
Was it helpful?

Solution

All you have to do is remove the user.save().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top