I was creating a user registration system in django1.8. But when I click register button on the form, it does not redirect to the success url. I am also not sure if this is the right way to save a user information in the database. Please recommend if there is a better way to approach user registration in django.
Models.py
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
age = models.IntegerField(blank=True)
gender_choices = (('M', 'Male'), ('F', 'Female'))
gender = models.CharField(max_length=1, choices=gender_choices, default='Male')
forms.py
from django import forms
from .models import UserProfile
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
exclude = ['user']
Views.py
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .forms import UserProfileForm
# Create your views here.
def registerView(request):
if request.method == "POST":
user_form = UserCreationForm(request.POST)
user_profile_form = UserProfileForm(request.POST)
if user_form.is_valid() and user_profile_form.is_valid():
new_user = user_form.save()
new_user_profile = user_profile_form.save()
return redirect(reverse('success'))
else:
return render(request, 'register.html', {'user_form': user_form, 'user_profile_form': user_profile_form})
else:
user_form = UserCreationForm(request.POST)
user_profile_form = UserProfileForm(request.POST)
return render(request, 'register.html', {'user_form': user_form, 'user_profile_form': user_profile_form})
def successView(request):
username = User.objects.get('username')
return render(request, 'success.html', {'username': username})
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.registerView, name='register'),
url(r'^success/$', views.successView, name='success')
]
register.html
<h1> Welcome </h1>
<form method="POST" action="{% url 'success' %}">
{% csrf_token %}
{{ user_form.as_p }}
{{ user_profile_form.as_p }}
<input type="button" value="Register"/>
</form>
success.html
<h4> Yo Mr...{{ username }}</h4>
<h1>Welcome</h1>
You need to make the following changes: