[Python] Account creation and authentication using Django

Discussão em 'Python' iniciado por Stack, Março 7, 2025.

  1. Stack

    Stack Membro Participativo

    I'm hitting a wall with this code. I am able to create a user and store the data. I can see the user in django admin panel. When I try logging into that user, I get a failure message. Ive tried changing the password in the django-admin panel. That did not work either. Here is my code. login.html

    {% extends "users/base.html" %}
    {% block title %} Login Page {% endblock title %}
    {% block content %}
    <div class="container">
    <div class="row justify-content-center align-items-center" style="min-height: 100vh;">
    <div class="col-lg-5">
    <div class="card shadow-lg border-0 rounded-lg">
    <div class="card-body">
    <h3 class="font-weight-light my-1 text-center">Sign In</h3>
    {% if form.errors %}
    <div class="alert alert-danger alert-dismissible" role="alert">
    <div id="form_errors">
    {% for key, value in form.errors.items %}
    <strong>{{ value }}</strong>
    {% endfor %}
    </div>
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
    </button>
    </div>
    {% endif %}
    <form method="POST">
    {% csrf_token %}
    <div class="form-row">
    <div class="col-md-10 offset-md-1">
    <div class="form-group">
    <label class="small mb-1">Username</label>
    {{ form.username }}
    </div>
    </div>
    </div>
    <div class="form-row">
    <div class="col-md-10 offset-md-1">
    <div class="form-group">
    <label class="small mb-1">Password</label>
    {{ form.password }}
    </div>
    </div>
    </div>
    <div class="form-row">
    <div class="col-md-10 offset-md-1">
    <div class="form-group">
    {{ form.remember_me }}
    <label> Remember me</label>
    </div>
    </div>
    </div>
    <div class="form-row">
    <div class="col-md-10 offset-md-1">
    <div class="form-group mt-0 mb-1">
    <button name="login" class="col-md-12 btn btn-dark" id="login">Sign in</button>
    </div>
    </div>
    </div>
    </form>
    </div>
    <div class="card-footer text-center">
    <div class="small">
    <a href="{% url 'register' %}">Don't have an account yet? Go to signup</a><br>
    <a href="{% url 'password_reset' %}"><i>Forgot Password?</i></a>
    </div>
    </div>
    </div>
    </div>
    </div>
    </div>
    {% endblock content %}


    forms.py

    from django import forms
    from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
    from .models import User
    from .models import STATE_CHOICES

    class RegisterForm(UserCreationForm):
    first_name = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'placeholder': 'First Name', 'class': 'form-control',}))
    last_name = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'placeholder': 'Last Name', 'class': 'form-control',}))
    username = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'form-control',}))
    email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Email', 'class': 'form-control',}))
    password1 = forms.CharField(max_length=100, required=True, widget=forms.PasswordInput, label="Password")
    password2 = forms.CharField(max_length=100, required=True, widget=forms.PasswordInput, label="Confirm Password")
    birthday = forms.DateField(required=True, widget=forms.DateInput(attrs={"class": "form-control", "placeholder": "MM/DD/YYYY"}))
    phone_number = forms.CharField(max_length=10, required=True, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Phone Number"}))
    address = forms.CharField(max_length=300, required=True, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Street Address"}))
    city = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "City"}))
    state = forms.ChoiceField(required=True, choices=STATE_CHOICES, widget=forms.Select(attrs={"class": "form-control"}))
    zip = forms.CharField(max_length=12, required=True, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Zip Code"}))
    is_contractor = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={"class": "form-check-input"}))

    class Meta:
    model = User
    fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'birthday', 'phone_number', 'address', 'city', 'state', 'zip', 'is_contractor']

    class LoginForm(AuthenticationForm):
    username = forms.CharField(max_length=100,
    required=True,
    widget=forms.TextInput(attrs={'placeholder': 'Username',
    'class': 'form-control',
    }))
    password = forms.CharField(max_length=50,
    required=True,
    widget=forms.PasswordInput(attrs={'placeholder': 'Password',
    'class': 'form-control',
    'data-toggle': 'password',
    'id': 'password',
    'name': 'password',
    }))
    remember_me = forms.BooleanField(required=False)

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

    class Meta:
    model = User
    fields = ['username', 'password', 'remember_me']

    class UpdateUserForm(forms.ModelForm):
    first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'placeholder': 'First Name', 'class': 'form-control',}))
    last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Last Name', 'class': 'form-control',}))
    username = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'form-control',}))
    email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email', 'class': 'form-control',}))
    password1 = forms.CharField(max_length=100, widget=forms.PasswordInput, label="Password")
    password2 = forms.CharField(max_length=100, widget=forms.PasswordInput, label="Confirm Password")
    birthday = forms.DateField(widget=forms.DateInput(attrs={"class": "form-control", "placeholder": "MM/DD/YYYY"}))
    phone_number = forms.CharField(max_length=10, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Phone Number"}))
    address = forms.CharField(max_length=300, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Street Address"}))
    city = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "City"}))
    state = forms.ChoiceField(choices=STATE_CHOICES, widget=forms.Select(attrs={"class": "form-control"}))
    zip = forms.CharField(max_length=12, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Zip Code"}))
    avatar = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control-file'}), required=False)

    class Meta:
    model = User
    fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'birthday', 'phone_number', 'address', 'city', 'state', 'zip', 'avatar']

    class UpdateProfileForm(forms.ModelForm):
    first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'placeholder': 'First Name', 'class': 'form-control',}))
    last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Last Name', 'class': 'form-control',}))
    username = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'form-control',}))
    email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email', 'class': 'form-control',}))
    password1 = forms.CharField(max_length=100, widget=forms.PasswordInput, label="Password")
    password2 = forms.CharField(max_length=100, widget=forms.PasswordInput, label="Confirm Password")
    birthday = forms.DateField(widget=forms.DateInput(attrs={"class": "form-control", "placeholder": "MM/DD/YYYY"}))
    phone_number = forms.CharField(max_length=10, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Phone Number"}))
    address = forms.CharField(max_length=300, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Street Address"}))
    city = forms.CharField(max_length=100, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "City"}))
    state = forms.ChoiceField(choices=STATE_CHOICES, widget=forms.Select(attrs={"class": "form-control"}))
    zip = forms.CharField(max_length=12, widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "Zip Code"}))
    avatar = forms.ImageField(widget=forms.FileInput(attrs={'class': 'form-control-file'}), required=False)

    class Meta:
    model = User
    fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'birthday', 'phone_number', 'address', 'city', 'state', 'zip', 'avatar']





    models.py

    from django.db import models
    from django.contrib.auth.models import AbstractUser, Group, Permission
    from PIL import Image
    from rest_framework_simplejwt.tokens import RefreshToken
    from django.contrib.gis.db import models as gis_models # Use GIS models
    from django.contrib.postgres.fields import HStoreField
    from django.db import connection
    from django.db.models.signals import post_migrate
    from django.dispatch import receiver

    STATE_CHOICES = (
    ('AL', 'Alabama'), ('AK', 'Alaska'), ('AZ', 'Arizona'),
    ('AR', 'Arkansas'), ('CA', 'California'), ('CO', 'Colorado'),
    ('CT', 'Connecticut'), ('DE', 'Delaware'), ('DC', 'District of Columbia'),
    ('FL', 'Florida'), ('GA', 'Georgia'), ('HI', 'Hawaii'), ('ID', 'Idaho'),
    ('IL', 'Illinois'), ('IN', 'Indiana'), ('IA', 'Iowa'), ('KS', 'Kansas'),
    ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('ME', 'Maine'), ('MD', 'Maryland'),
    ('MA', 'Massachusetts'), ('MI', 'Michigan'), ('MN', 'Minnesota'),
    ('MS', 'Mississippi'), ('MO', 'Missouri'), ('MT', 'Montana'),
    ('NE', 'Nebraska'), ('NV', 'Nevada'), ('NH', 'New Hampshire'),
    ('NJ', 'New Jersey'), ('NM', 'New Mexico'), ('NY', 'New York'),
    ('NC', 'North Carolina'), ('ND', 'North Dakota'), ('OH', 'Ohio'),
    ('OK', 'Oklahoma'), ('OR', 'Oregon'), ('PA', 'Pennsylvania'),
    ('RI', 'Rhode Island'), ('SC', 'South Carolina'), ('SD', 'South Dakota'),
    ('TN', 'Tennessee'), ('TX', 'Texas'), ('UT', 'Utah'), ('VT', 'Vermont'),
    ('VA', 'Virginia'), ('WA', 'Washington'), ('WV', 'West Virginia'),
    ('WI', 'Wisconsin'), ('WY', 'Wyoming'),
    )

    class User(AbstractUser):
    phone_number = models.CharField(max_length=10, blank=True, null=True)
    address = models.CharField(max_length=300, blank=True, null=True)
    city = models.CharField(max_length=100, blank=True, null=True)
    state = models.CharField(max_length=2, choices=STATE_CHOICES, blank=True, null=True)
    zip = models.CharField(max_length=100, blank=True, null=True)
    bio = models.TextField(blank=True, null=True)
    company_name = models.CharField(max_length=255, blank=True, null=True)
    is_contractor = models.BooleanField(default=False)
    avatar = models.ImageField(default='default.jpg', upload_to='media')
    birthday = models.DateField(blank=True, null=True)

    groups = models.ManyToManyField(
    Group,
    related_name='custom_user_set', # Change related_name to avoid conflict
    blank=True,
    help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.',
    related_query_name='user',
    )
    user_permissions = models.ManyToManyField(
    Permission,
    related_name='custom_user_permissions_set', # Change related_name to avoid conflict
    blank=True,
    help_text='Specific permissions for this user.',
    related_query_name='user',
    )

    def get_tokens(self):
    refresh = RefreshToken.for_user(self)
    return {
    'refresh': str(refresh),
    'access': str(refresh.access_token),
    }

    def save(self, *args, **kwargs):
    super().save(*args, **kwargs)

    img = Image.open(self.avatar.path)

    if img.height > 100 or img.width > 100:
    new_img = (100, 100)
    img.thumbnail(new_img)
    img.save(self.avatar.path)

    def __str__(self):
    return self.username


    views.py

    class CustomLoginView(LoginView):
    form_class = LoginForm
    template_name = 'users/login.html'

    def form_valid(self, form):
    remember_me = form.cleaned_data.get('remember_me')
    if not remember_me:
    self.request.session.set_expiry(0)
    self.request.session.modified = True
    return super(CustomLoginView, self).form_valid(form)
    def login_view(request):
    if request.method == 'POST':
    form = LoginForm(request.POST)
    if form.is_valid():
    username = form.cleaned_data.get('username')
    password = form.cleaned_data.get('password')
    user = authenticate(request, username=username, password=password)
    if user is not None:
    if user.is_active:
    login(request, user)
    return redirect('home')
    else:
    form.add_error(None, "This account is inactive.")
    else:
    if not get_user_model().objects.filter(username=username).exists():
    form.add_error(None, "Invalid username or password")
    else:
    user_obj = get_user_model().objects.get(username=username)
    if check_password(password, user_obj.password):
    form.add_error(None, "This account is inactive.")
    else:
    form.add_error(None, "Invalid username or password")
    else:
    form.add_error(None, "Form validation failed.")
    else:
    form = LoginForm()
    return render(request, 'users/login.html', {'form': form})


    settings.py

    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users.apps.UsersConfig',
    'social_django',
    'django.contrib.postgres',

    AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',



    If anyone could help find what I am missing, I would be much appreciated I'm using Postgresql if that matters.

    This is the gobbly gook log I tried to implement to find my issue, but it tells me nothing

    (0.002) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2025-03-07T01:50:50.049020+00:00'::timestamptz AND "django_session"."session_key" = 'kbfks1dttfovy17uf8q850as10stpzxq') LIMIT 21; args=(datetime.datetime(2025, 3, 7, 1, 50, 50, 49020, tzinfo=datetime.timezone.utc), 'kbfks1dttfovy17uf8q850as10stpzxq'); alias=default (0.002) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2025-03-07T01:50:50.049020+00:00'::timestamptz AND "django_session"."session_key" = 'kbfks1dttfovy17uf8q850as10stpzxq') LIMIT 21; args=(datetime.datetime(2025, 3, 7, 1, 50, 50, 49020, tzinfo=datetime.timezone.utc), 'kbfks1dttfovy17uf8q850as10stpzxq'); alias=default (0.000) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 6 LIMIT 21; args=(6,); alias=default (0.000) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 6 LIMIT 21; args=(6,); alias=default "POST /login/ HTTP/1.1" 200 6474 "POST /login/ HTTP/1.1" 200 6474


    url.py

    #url.py users app
    path('login/', CustomLoginView.as_view(), name='login'),

    #url.py in project
    path('login/', CustomLoginView.as_view(redirect_authenticated_user=True, template_name='users/login.html',
    authentication_form=LoginForm), name='login'),

    Continue reading...

Compartilhe esta Página