Hey Kean, 
I am already working on some Djago user authentication . Below are my codes, 
may be they would help you.
views.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from templates.authenticate.forms import SignUpForm


def home(request):
    return render(request, 'authenticate/home.html', {})


def login_user(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            messages.success(request, 'you have loggedin success')
            return redirect('home')
        else:
            messages.success(request, 'Error loggin in....')
            return redirect('login')

    else:
        return render(request, 'authenticate/login.html', {})


def logout_user(request):
    logout(request)
    messages.success(request, 'You have been logged out...')
    return redirect('home')


def register_user(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = authenticate(request, username=username, password=password)
            login(request, user)
            messages.success(request, 'registration successfull....')
            return redirect('home')
    else:
        form = SignUpForm()
    context = {'form': form}
    return render(request, 'authenticate/register.html', context)


def edit_profile(request):
    if request.method == 'POST':
        form = UserChangeForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = authenticate(request, username=username, password=password)
            login(request, user)
            messages.success(request, 'registration successfull....')
            return redirect('home')
    else:
        form = UserChangeForm(instance=request.user)

    context = {'form': form}
    return render(request, 'authenticate/edit_profile.html', context)forms.py
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User


class SignUpForm(UserCreationForm):
    email = forms.EmailField(widget=forms.TextInput(attrs={'class': 
'form-control', 'placeholder': 'email address'}))
    first_name = forms.CharField(max_length=100, 
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'first 
name'}))
    last_name = forms.CharField(max_length=100, 
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'last 
name'}))


class Meta:
    model = User
    fields = ('username', 'first_name', 'last_name', 'email', 'password1', 
'password2')


def __init__(self, *args, **kwargs):
    super(SignUpForm, self).__init__(*args, **kwargs)

    self.fields['username'].widget.attrs['class'] = 'form-control'
    self.fields['password1'].widget.attrs['class'] = 'form-control'
    self.fields['password2'].widget.attrs['class'] = 'form-control'
I have also attached the HTML pages with this email in the txt format. I hope 
that helps you. Below is the django official doc link that I am referring.
https://docs.djangoproject.com/en/2.2/topics/auth/default/#auth-web-requests



Regards,
Amitesh Sahay 

    On Wednesday, 28 August, 2019, 10:24:38 pm IST, Kean <kean...@gmail.com> 
wrote:  
 
 Hi,New to Django.
I've created a registration form which inherits from a User form.The issue is 
none of the validators are working. e.g reporting to user password miss-match, 
or any other error if user enters data incorrect to validation.The form simply 
validates with errors and redirect user to to their user page (as defined,).
Please can anyone help or advise, as I though the validators were an inherent 
part of the django forms?
forms.py
class CRegisterForm(UserCreationForm):    email = 
forms.EmailField(max_length=30, required=True)
    class Meta:        model = User        fields = ['username', 'email', 
'password1', 'password2']
views.py
def cregister(request):    if request.method == "POST":        form = 
CRegisterForm(request.POST)        if form.is_valid():            data = 
form.cleaned_data            form.save()        return redirect('cpage')    
else:        form = CRegisterForm()        return render(request, 
'cregister.html', {'form': form})
urls.py
 path('login/customer/', views.cpage, name='cpage'),

html
{% load crispy_forms_tags %}<!DOCTYPE html><html><head> 
<title>Customer</title></head> <br><body> <div> <div class = "container" > 
<form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend 
class="border-bottom mb-3">Customer Login</legend> {{ form|crispy }}  
</fieldset>  <div class="form-group"> <button class="btn btn-outline-info" 
type="submit">Login</button> </div> {% if messages %}   {% for messages in 
messages %}     <div class="alert alert-{{ message.tags }}">      {{ message }} 
    </div>     {% endfor %}     {% endif %} </form> <div class="border-top 
pt-3"> <small class = "text-muted"> Need a customer account <a class="ml-2" 
href="cregister">Customer register</a> </small> </div> </div> </body></html>


Best,
K



 


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a4739118-05b9-4706-b1cb-08062cc6f93d%40googlegroups.com.
  

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1441704490.2800369.1567014644390%40mail.yahoo.com.
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, 
shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" 
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"; 
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
 crossorigin="anonymous">

    <title>Hello, world!</title>
  </head>
  <body>
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <a class="navbar-brand" href="{% url 'home'%}">Nagraj</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" 
data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" 
aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav ml-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span 
class="sr-only">(current)</span></a>
      </li>
        {% if user.is_authenticated %}
      <li class="nav-item">
        <a class="nav-link" href="{%  url 'logout' %}">logout</a>
      </li>
        {% else %}
            <li class="nav-item">
            <a class="nav-link" href="{% url 'login' %}">login</a>
            </li>

            <li class="nav-item">
            <a class="nav-link" href="{% url 'register' %}">register</a>
            </li>

            <li class="nav-item">
            <a class="nav-link" href="{% url 'edit' %}">edit</a>
            </li>

        {% endif %}

      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" 
aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" 
type="submit">Search</button>
    </form>
  </div>
</nav>
  <br/>
  <div class="container">
    {% if messages %}
        {% for message in messages %}
            <div class="alert alert-warning alert-dismissable" role="alert">
                <button class="close" data-dismiss="alert">
                        <small><sup>x</sup></small>
                </button>
            {{ message }}
        </div>
  {% endfor %}
  {% endif %}
    {% block content %}
    {% endblock %}

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"; 
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
 crossorigin="anonymous"></script>
    <script 
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"; 
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
 crossorigin="anonymous"></script>
    <script 
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"; 
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
 crossorigin="anonymous"></script>
  </div></body>
</html>
{% extends 'authenticate/base.html' %}
{% block content %}
    <h2 class="text-center">Edit Profile</h2>
    <div class="col-md-6 offset-md-3">
    <form method="POST" action="{% url 'register' %}">
    {%  csrf_token %}
        {% if form.errors %}
            <div class="alert alert-warning alert-dismissable" role="alert">
            <button class="close" data-dismiss="alert">
                <small><sup>x</sup></small>
            </button>
        <p>Your form has errors, please fix</p>
            {% for fields in form %}
                {% if fields.errors %}
                    {{ fields.errors }}
                {% endif %}
            {% endfor %}
        {%  endif %}

    {{ form.as_p }}
    <input type="submit" value="Register" class="btn btn-secondary">
        </div></form>
    </div>
{% endblock %}
{% extends 'authenticate/base.html' %}
{% block content %}
        <button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-secondary">Secondary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-danger">Danger</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-light">Light</button>
<button type="button" class="btn btn-dark">Dark</button>
<button type="button" class="btn btn-link">Link</button>
    <nav aria-label="Page navigation example">
  <ul class="pagination">
    <li class="page-item"><a class="page-link" href="#">Previous</a></li>
    <li class="page-item"><a class="page-link" href="#">1</a></li>
    <li class="page-item"><a class="page-link" href="#">2</a></li>
    <li class="page-item"><a class="page-link" href="#">3</a></li>
    <li class="page-item"><a class="page-link" href="#">Next</a></li>
  </ul>
</nav>
    <h2>This is a home page</h2>
    {% if user.is_authenticated %}
        <p>Name: {{ user.first_name }} {{ user.last_name }}</p>
        <p>Username: {{ user.username }}</p>
        <p>Password: {{ user.password }}</p>
        <p>Email: {{ user.email }}</p>
    {% endif %}
{% endblock %}
{% extends 'authenticate/base.html' %}
{% block content %}

<h1 class="text-center">Login</h1>>
    <div class="col-md-6 offset-md-3">

<form method="POST">
    {% csrf_token %}
  <div class="form-group">

    <input type="text" class="form-control" placeholder="Enter username" 
name="username">

  </div>

  <div class="form-group">

    <input type="password" class="form-control" placeholder="Password" 
name="password">
  </div>


  <button type="submit" class="btn btn-tertiary">login</button>
</form>
    </div>

{% endblock %}
{% extends 'authenticate/base.html' %}
{% block content %}
    <h2 class="text-center">Registration</h2>
    <div class="col-md-6 offset-md-3">
    <form method="POST" action="{% url 'register' %}">
    {%  csrf_token %}
        {% if form.errors %}
            <div class="alert alert-warning alert-dismissable" role="alert">
            <button class="close" date-dismiss="alert">
                <small><sup>x</sup></small>
            </button>
        <p>Your form has errors, please fix</p>
            {% for fields in form %}
                {% if fields.errors %}
                    {{ fields.errors }}
                {% endif %}
            {% endfor %}
        {%  endif %}

    {{ form.as_p }}
    <input type="submit" value="Register" class="btn btn-secondary">
        </div></form>
    </div>
{% endblock %}

Reply via email to