django.contrib.auth get_user_model Example Code

Django's get_user_model function is the appropriate way of referencing the Django User model rather than a direct import of User.

Example 1 from dccnsys

dccnsys is a conference registration web app built in Django. The code is open source under the MIT license.

dccnsys / wwwdccn / registration / views.py

## views.py
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect

from users.models import generate_avatar
from users.forms import PersonalForm, ProfessionalForm, SubscriptionsForm

User = get_user_model()


@login_required
def personal(request):
    profile = request.user.profile
    if request.method == 'POST':
        form = PersonalForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            profile.avatar = generate_avatar(profile)
            profile.save()
            return redirect('register-professional')
    else:
        form = PersonalForm(instance=profile)
    return render(request, 'registration/personal.html', {
        'form': form
    })

@login_required
def professional(request):
    profile = request.user.profile
    if request.method == 'POST':
        form = ProfessionalForm(request.POST, instance=profile)
        if form.is_valid():
            form.save()
            return redirect('register-subscriptions')
    else:
        form = ProfessionalForm(instance=profile)
    return render(request, 'registration/professional.html', {
        'form': form
    })


@login_required
def subscriptions(request):
    subscriptions = request.user.subscriptions
    if request.method == 'POST':
        form = SubscriptionsForm(request.POST, instance=subscriptions)
        if form.is_valid():
            form.save()
            request.user.has_finished_registration = True
            request.user.save()
            return redirect('home')
    else:
        form = SubscriptionsForm(instance=subscriptions)
    return render(request, 'registration/subscriptions.html', {
        'form': form
    })

Sign up for a monthly email with Full Stack Python tutorials. No spam ever.

Learn More Python

Introduction to Ansible video course logo.

Deploy web apps with the Ansible configuration management tool.

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via newsletter, Twitter & Facebook.

Matt Makai 2012-2019