Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

django login code

from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        # Redirect to a success page.
        ...
    else:
        # Return an 'invalid login' error message.
        ...
Comment

django login page

from django.contrib.auth import authenticate, login
fro django.shortcuts import render, redirect

def login_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        # Redirect to a success page.
        return redirect('/')
        ...
    else:
        # Return an 'invalid login' error message.
        ...
        context = {'error':'Invalid username or password.'}
        return render(request, '/login.html', context)
        
               
Comment

django loginview?


#loginView
from django.contrib.auth.views import LoginView    

class AdminLogin(LoginView):
    template_name = 'LoginView_form.html'

Comment

django login

def login_view(request):
    if request.method == 'GET':
        cache.set('next', request.GET.get('next', None))

    if request.method == 'POST':
        # do your checks here

        login(request, user)

        next_url = cache.get('next')
        if next_url:
            cache.delete('next')
            return HttpResponseRedirect(next_url)

    return render(request, 'account/login.html')
Comment

django loginview

class Login(LoginView):
    template_name = "registration/login.html"
    def get_context_data(self, **kwargs):
        context = super(Login,self).get_context_data(**kwargs)
        page_title = 'Login'
        context.update({
            "page_title":page_title
         })
        return context
Comment

Python Django Login register

// go to templates - includes folder - alerts.html
{% if messages %}
<ul class="messages">
  {% for message in messages %}
  <li{% if message.tags %} class="{{message.tags}}"{% endif %}>
    {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %} Important: {% endif %}
    {{ message }}
  </li>
  {% endfor %}
</ul>
{% endif %}
// go to settings.py 
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
    messages.INFO: 'danger',
}
// go to templates - accounts folder - register.html 
 <center>
<div class="col-lg-5 order-1 order-lg-2">

  <div class="row justify-content-md-center">
    <div class="col-md-9" style="margin-bottom: 250px; margin-top: 150px;">
      <div class="featured-box featured-box-primary text-start mt-0">
        <div class="box-content">
          {% include 'includes/alerts.html'%}
          <h4 class="color-primary font-weight-semibold text-4 text-uppercase mb-3">Register An Account</h4>
          <form action="{% url 'register'%}" id="frmSignUp" method="POST" class="needs-validation">
            {% csrf_token %}

            <div class="row">
              <div class="form-group col-lg-6">
                <label class="form-label">First Name</label>
                {{ form.first_name }}
              </div>
              <div class="form-group col-lg-6">
                <label class="form-label">Last Name</label>
                {{ form.last_name }}
              </div>
            </div>

            <div class="row">
              <div class="form-group col-lg-6">
                <label class="form-label">Email</label>
                {{ form.email }}
              </div>
              <div class="form-group col-lg-6">
                <label class="form-label">Phone Number</label>
                {{ form.phone_number }}
              </div>
            </div>
            <div class="row">
              <div class="form-group col-lg-6">
                <label class="form-label">Password</label>
                {{ form.password}}
              </div>
              <div class="form-group col-lg-6">
                <label class="form-label">Re-enter Password</label>
                {{ form.confimr_password}}
              </div>
            </div>
            <div class="row">
              <div class="form-group col-lg-9">
                <div class="custom-control custom-checkbox">
                  <input type="checkbox" name="terms" class="custom-control-input" id="terms">
                  <label class="custom-control-label text-2" for="terms">I have read and agree to the <a href="#">terms of service</a></label>
                </div>
              </div>
              <div class="form-group col-lg-3">
                <input type="submit" value="Register" class="btn btn-primary btn-modern float-end" data-loading-text="Loading...">
              </div>
            </div>
            {{ form.email.errors}}
            {{ form.non_field_errors }}
          </form>
        </div>
      </div>
    </div>
  </div>

</div></center>
// go to accounts folder APP - forms.py 
from django import forms
from .models import Account

class RegistrationForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput(attrs={
        'placeholder': 'Enter Password',
        'class': 'form-control'
    }))
    confimr_password = forms.CharField(widget=forms.PasswordInput(attrs={
        'placeholder': 'Confirm Password'
    }))
    class Meta:
        model = Account
        fields = ['first_name', 'last_name', 'phone_number', 'email', 'password']

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        self.fields['first_name'].widget.attrs['placeholder'] = 'Enter Firstname'
        self.fields['last_name'].widget.attrs['placeholder'] = 'Enter Lastname'
        self.fields['email'].widget.attrs['placeholder'] = 'Enter Email'
        self.fields['phone_number'].widget.attrs['placeholder'] = 'Enter Phone Number'
        for field in self.fields:
            self.fields[field].widget.attrs['class'] = 'form-control'

    // Use to verify match password        
    def clean(self):
        cleaned_data = super(RegistrationForm, self).clean()
        password = cleaned_data.get('password')
        confimr_password = cleaned_data.get('confimr_password')

        if password != confimr_password:
            raise forms.ValidationError(
                "Password does not match!"
            )

// go to accounts folder APP - urls.py 
 from django.urls import path
from . import views

urlpatterns = [
    path('register/', views.register, name='register'),
    path('login/', views.login, name='login'),
    path('logout/', views.logout, name='logout'),
]
//  
Comment

login system in django

LOGOUT_REDIRECT_URL = 'your_url'
Comment

login view django

from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth.forms import AuthenticationForm
from django.shortcuts import render, redirect

def login_view(request):
    if request.method == "POST":
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password= password)
            if user is not None:
                login(request, user)
                messages.info(request, f"You are now logged in as {username}.")
                return redirect ('inventory:home')
            else:
                messages.error(request, "Invalid username or password")
    else:
        messages.error(request, "Invalid username or password")
    form = AuthenticationForm()
    return render(request, 'registration/login.html', context={"login_form":form})
Comment

PREVIOUS NEXT
Code Example
Python :: python string replace variable 
Python :: tables in python 
Python :: pandas access multiindex column 
Python :: python list contains 
Python :: program to add first and last digit of a number in python 
Python :: python towers of hanoi recursive 
Python :: python class arbitrary arguments 
Python :: python get total gpu memory 
Python :: cannot reshape array of size 2137674 into shape (1024,512,3,3) 
Python :: python sort an array 
Python :: python find if strings are anagrams 
Python :: soustraire deux listes python 
Python :: leetcode matrix diagonal sum in python 
Python :: numpy copy a array vertical 
Python :: how to union value without the same value in numpy 
Python :: get first element of tuple python 
Python :: numpy find mean of array 
Python :: django authenticate with email 
Python :: .first() in django 
Python :: code 
Python :: keyboard write python 
Python :: check if list is in ascending order python 
Python :: make value of two tables unique django 
Python :: doc strings python 
Python :: argparse positional arguments 
Python :: PyPip pygame 
Python :: calculate the shortest path of a graph in python 
Python :: python dictoinary add value 
Python :: snapchat api in python 
Python :: requests sessions 
ADD CONTENT
Topic
Content
Source link
Name
6+5 =