Maninder Singh
Maninder Singh

Reputation: 485

Django:What is best way to import my Custom-User in views.py?

Actually i have created my own custom-user (MyUser) in models.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class MyUser(AbstractUser):
    country=models.CharField(max_length=20)

settings.py

AUTH_USER_MODEL = 'new_user.MyUser'

I created a simple function in views.py to create new users.

from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.contrib.auth import get_user_model
from django.conf import settings

def save_account(request):
    MyUser=get_user_model()
    if request.method == "POST":
        name=request.POST.get("name")
        email=request.POST.get("email")
        password1=request.POST.get("password1")
        password2=request.POST.get("confirm-password")
        country=request.POST.get("country")
        new_user=MyUser.objects.create_user(username=name,email=email,password=password1,country=country)
        new_user.save()
        return redirect('/')
    else:
        return HttpResponse("404 Not Found")

1. Here i use get_user_model() function to get my currently custom-user.

2. I have second option to get my custom user just by importing MyUser model from models.py and then use it.

from .models import MyUser

3. I have third option to get custom-user just by importing AUTH_USER_MODEL directly from settings.py and use it like in this way.

from django.conf import settings
MyUser=settings.AUTH_USER_MODEL

but third option returning a string instead of returning my custom-user.but why?

I just want to know that which option is best to import custom-user in views.py and why?

Upvotes: 0

Views: 1860

Answers (1)

Alasdair
Alasdair

Reputation: 309089

Your first two options are both ok. Using get_user_model makes it easier to reuse the app without changing the import. However many Django projects are not meant to be re-used, in which case the explicit import makes it clearer where the user model is imported from.

settings.AUTH_USER_MODEL is meant to be a string. You set it to a string when you did AUTH_USER_MODEL = 'new_user.MyUser', and Django doesn't automatically change it to the model instance when you access it. It's useful in foreign keys because it means you don't need to import the model. For example:

class MyModel(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )

Upvotes: 3

Related Questions