Home > Back-end >  Which is the most commonly used way to implement user signup and login?
Which is the most commonly used way to implement user signup and login?

Time:09-16

I'm starting out with Django development and I feel very confused and lost about all the ways you can implement the same thing. (or I may be just stupid) It all is very jumbled in my head right now (Class-based forms? Class-based views? Function-based views with Class-based forms? Custom HTML forms which are bound to Forms class and then etc etc etc...)


So far these are all the intertwined options that I see and they confuse me a lot:

  • Plain HTML forms which are then bound to the Form instance in views for validation (?). Every view is custom. (I like this one the best because I don't find any joy in using {{ form }} in templates, plus this one seem to be straightforward for me) Is forms.py not used when you implement forms that way?

  • include('django.contrib.auth.urls') for login with custom templates (in which you when use {{ form }} and then something else for signup because there is no same built-in thing for signing up

  • UserCreationForm but you have to extend it somehow if you want to add more fields (why are there built-in views for authentication but not for user creation btw?)

  • Custom class-based forms if you want to use them with custom user models

What should I use if there would be extra data associated with User on registration? What is the most commonly way Django developers use in general?


Sorry if I'm not making much sense, I'm a novice developer and overwhelmed everytime there are just too many ways to do the same thing. :-)

CodePudding user response:

In my opinion the most common way to implement signup and login is through the built in Django Functions such as : include('django.contrib.auth.urls') and UserCreationForm

I have actually got a template that I use when I start a new project and would like to add a login and signup page, here's the link

I hope this helps ;)

CodePudding user response:

The way I know is using built-in Django contrib module like UserCreationForm from django.contrib.auth.forms for signup function and AuthenticationForm for login. Below are my codes in views.py

from django.contrib.auth.forms import (
    AuthenticationForm, 
    UserCreationForm,
)
from django.contrib.auth import login as auth_login,

@require_http_methods(['GET', 'POST'])    
def signup(request):
    if request.user.is_authenticated:
        return redirect('articles:index')
        
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            auth_login(request, user)
            return redirect('articles:index')       
    else:
        form = UserCreationForm()
    context = {
        'form': form,
    }
    return render(request,'accounts/signup.html', context)

@require_http_methods(['GET','POST'])
def login(request):
    if request.user.is_authenticated:
        return redirect('articles:index')

    if request.method == 'POST':
        form = AuthenticationForm(request, request.POST)
        if form.is_valid():
            auth_login(request, form.get_user())
            return redirect(request.GET.get('next') or 'articles:index')
    else:
        form = AuthenticationForm()
    context = {
        'form':form,
    }
    return render(request, 'accounts/login.html', context)

CodePudding user response:

You have posted a detailed question, let us concentrate at this right now and we can go from there

What should I use if there would be extra data associated with User on registration? What is the most commonly way Django developers use in general?

Your best bet is to refer Django docs which will definitely give you the best advice out there. So the docs here read

If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you. This model behaves identically to the default user model, but you’ll be able to customize it in the future if the need arises.

So you have to create a Custom User Model. How do you do that? well you use AbstractUser. Here is a step-wise brief breakup

Note - Do not run migrate command to configure the database. Migrate after creating the Custom User Model.

  • Create a new Django project
  • Create Custom User Model App - app name will be -> users

This involves 4 steps

  1. update settings.py like so

    INSTALLED_APPS = [
        #Built In Apps
        ...
        #Custom Apps
        'users.apps.UsersConfig',
    ]
    ...
    # At the end of settings.py file
    AUTH_USER_MODEL = 'users.CustomUser'
    
  2. create a new CustomUser model. Let us use a new custom field. Say Age - users/models.py

    from django.contrib.auth.models import AbstractUser
    from django.db import models
    
    class CustomUser(AbstractUser):
        age = models.PositiveIntegerField(null=True, blank=True)
    
  3. create new forms for UserCreationForm and UserChangeForm

Remember the two ways in which we would interact with our new CustomUser model.

  1. When a user signs up for a new account on our website.
  2. Within the admin app to modify existing users.

So we update the two built-in forms for this functionality:

  1. UserCreationForm
  2. UserChangeForm.

So - create a new file in the users app called forms.py - users/forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm):
        model = CustomUser
        fields = UserCreationForm.Meta.fields   ('age',)

class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = UserChangeForm.Meta.fields

Here - Meta class is used to override the default fields by setting the model to CustomUser.

Finally

  1. Update admin.py file since Admin is tightly coupled to the default User model -> users/admin.py

    from django.contrib import admin
    from django.contrib.auth.admin import UserAdmin
    from .forms import CustomUserCreationForm, CustomUserChangeForm
    from .models import CustomUser
    
    class CustomUserAdmin(UserAdmin):
        add_form = CustomUserCreationForm
        form = CustomUserChangeForm
        model = CustomUser
        list_display = ['email', 'username', 'age', 'is_staff', ]
    
    admin.site.register(CustomUser, CustomUserAdmin)
    

Now migrate to configure your Database and create a new superuser and test it.


Hope this gives you a starting point on how to go ahead. Work on this am sure your other doubts will be eventually resolved.

  • Related