
First part of a series of one minute guides. In this episode: signup view for a custom User model with some additional fields.
Add custom fields to User
Work with any app you want (I will have anyapp
).
anyapp/models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUserManager(UserManager):
pass
class CustomUser(AbstractUser):
objects = CustomUserManager()
bio = models.TextField(max_length=500, blank=True)
birth_date = models.DateField(null=True, blank=True)
anyapp/forms.py:
from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ('username', 'email', 'bio', 'birth_date',)
Somewhere in project/settings.py:
AUTH_USER_MODEL = 'anyapp.CustomUser'
Make a Signup page
anyapp/views.py:
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from .forms import CustomUserCreationForm
from django.http import HttpResponse
def signup(request):
page_content = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Signup</title></head><body><section><h2>Sign up</h2><form method="post">{% csrf_token %}{{ form.as_p }}<button type="submit">Sign up</button></form></section></body></html>'
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('success')
else:
form = CustomUserCreationForm()
return render(request, 'user/signup.html', {'form': form})
def success(request):
page_content = '<head><title>Success!</title></head><body style="background-color:#DBE0F1;"><div style="margin-top:20px; text-align:center;"><h1>Welcome!</h1><p style="margin-bottom:10px;">Take a look at this good boy.</p><blockquote class="imgur-embed-pub" lang="en" data-id="a/eUu1OvC"><a href="//imgur.com/a/eUu1OvC">My boy Link keeping cool in the heat</a></blockquote><script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script></div></body>'
return HttpResponse(page_content, content_type='text/html')
anyapp/urls.py:
from django.http import HttpResponse
import .views as auth_views
urlpatterns = [
path('signup/', auth_views.signup, name='signup'),
path('success/', auth_views.auccess, name='success'),
]
Success!

Side note: I don’t like using email as login, as in this day and age I don’t see email as something absolutely necessary. There’re other way to make a user leave reveal their email I prefer more. In next parts of the series I will show email as login version as well.
[…] will be using a custom AbstractUser model, I talked about it here. Don’t forget to set AUTH_USER_MODEL = 'yourapp.CustomUser' in the […]
LikeLike