article

Tuesday, April 14, 2020

Django - Create User Sign Up


Django - Create User Sign Up


 
#views.py
from django.shortcuts import render, redirect  

# Create your views here.   
from django.contrib.auth import login, authenticate
from myapp.forms import SignUpForm

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(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('/')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})
 
def home(request):
    return render(request, 'home.html')
 
#forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.')

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', )
 
#urls.py
from django.contrib import admin  
from django.urls import path  
from myapp import views  

urlpatterns = [  
    path('admin/', admin.site.urls),  
    path('signup', views.signup),
    path('', views.home),
]  
<!DOCTYPE html> <html lang="en">
//templates/signup.html
<head>  
<meta charset="UTF-8">  
<title>Django - Create User Sign Up</title> 
</head> 
<body>
<div class="container">
 <div class="row">
  <div class="col-md-12">
        <h2>Django - Create User Sign Up</h2> 
  <form method="post">
    {% csrf_token %}
  <!-- {{ form.as_p }} -->
    {% for field in form %}
      <p>
        {{ field.label_tag }}<br>
        {{ field }}
        {% if field.help_text %}
          <small style="color: grey">{{ field.help_text }}</small>
        {% endif %}
        {% for error in field.errors %}
          <p style="color: red">{{ error }}</p>
        {% endfor %}
      </p>
    {% endfor %}
    <button type="submit">Sign up</button>
  </form>
  
 </div> 
 </div> 
</div> 
</body> 
</html>

Related Post