Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a signup view using Class based views in Django?

When I started to use Django, I was using FBVs ( Function Based Views ) for pretty much everything including signing up for new users.

But as I delved deep more into projects, I realized that Class-Based Views are usually better for large projects as they are more clean and maintainable but this is not to say that FBVs aren't.

Anyway, I migrated most of my whole project's views to Class-Based Views except for one that was a little confusing, the SignUpView.

like image 819
Roast Biter Avatar asked Dec 08 '22 10:12

Roast Biter


2 Answers

In order to make SignUpView in Django, you need to utilize CreateView and SuccessMessageMixin for creating new users as well as displaying a success message that confirms the account was created successfully.

Here's the code :

views.py:

from .forms import UserRegisterForm
from django.views.generic.edit import CreateView

class SignUpView(SuccessMessageMixin, CreateView):
  template_name = 'users/register.html'
  success_url = reverse_lazy('login')
  form_class = UserRegisterForm
  success_message = "Your profile was created successfully"

and, the forms.py:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class UserRegisterForm(UserCreationForm):
  email = forms.EmailField()

  class Meta:
      model = User
      fields = ['username', 'email', 'first_name']
like image 130
Roast Biter Avatar answered Dec 28 '22 06:12

Roast Biter


You can use Django's CreateView for creating a new user object.

# accounts/views.py
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic


class SignUp(generic.CreateView):
    form_class = UserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

For more info, check https://learndjango.com/tutorials/django-signup-tutorial

like image 31
Edgar Vardanyan Avatar answered Dec 28 '22 07:12

Edgar Vardanyan