Проблема с формой входа в систему Django: форма недействительна, несмотря на правильные учетные данныеPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Проблема с формой входа в систему Django: форма недействительна, несмотря на правильные учетные данные

Сообщение Anonymous »

Я столкнулся с проблемой с моей формой входа в Django. Несмотря на предоставление правильных учетных данных, форма последовательно возвращается как недействительную. Вот подробное описание моей настройки и проблемы, с которой я сталкиваюсь. Аутентификация для обработки входа пользователя. Моя цель - аутентифицировать пользователей и перенаправить их на определенную страницу после успешного входа в систему. Тем не менее, проверка формы не выполняется, даже если учетные данные точны, а пользователь существует в базе данных.
from django import forms
from .models import UserRegister
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm , AuthenticationForm
from django.core.exceptions import ValidationError

class UserRegisterForm(UserCreationForm):
username = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'input-group'}))
email = forms.EmailField(max_length=70, required=True, widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'input-group'}))
password1 = forms.CharField(max_length=128, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'input-group', 'id': 'password'}))
password2 = forms.CharField(max_length=128, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password', 'class': 'input-group', 'id': 'password'}))

class Meta:
model = UserRegister
fields = ['username', 'email', 'password1', 'password2']
error_messages = {
"password_mismatch": "Conform Password Does not match with Password"
}

def clean_email(self):
email = self.cleaned_data.get('email')
if UserRegister.objects.filter(email=email).exists():
raise ValidationError('This email address is already in use.')
return email

def clean_username(self):
username = self.cleaned_data.get('username')
if UserRegister.objects.filter(username=username).exists():
raise ValidationError('This username is already in use.')
return username

def clean_password2(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1 != password2:
raise ValidationError(self.error_messages['password_mismatch'], code='password_mismatch')
return password2

class UserLoginForm(AuthenticationForm):
username = forms.CharField(max_length=50, required=True ,widget=forms.TextInput(attrs={'placeholder':'Username','class':'input-group'}))
password = forms.CharField(max_length=128,required=True,widget=forms.PasswordInput(attrs={'placeholder':'Password','class':'input-group'}))

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

< /code>
views.py

from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect, Http404
from .forms import UserRegisterForm, UserLoginForm
from django.contrib import messages
from .models import UserRegister
from django.contrib.auth import authenticate, login

# Create your views here.

products = [
{
"slug": "Mustang-GT",
"About": """The Ford Mustang GT in its stunning white color is nothing short of a modern-day classic. From the moment you lay eyes on
it, the Mustang's sleek and muscular design commands attention and admiration. The pristine white finish only adds to its allure,
giving it a timeless, elegant look that stands out on the road. Performance: Under the hood, the Mustang GT roars to life with its
5.0-liter V8 engine, delivering a thrilling 450 horsepower. The acceleration is exhilarating, and the handling is precise, making
every drive a memorable experience. Whether you're cruising down the highway or taking on winding roads, the Mustang GT's performance
is unmatched in its class. Interior: Step inside, and you're greeted with a blend of classic muscle car ambiance and modern
sophistication. The leather seats are comfortable and supportive, perfect for long drives. The dashboard is well-designed,
with intuitive controls and a high-quality infotainment system that keeps you connected and entertained. Driving Experience:
Driving the Mustang GT is an absolute joy. The sound of the engine is music to any car enthusiast's ears, and the responsive
steering makes you feel in complete control. The car's suspension strikes a perfect balance between comfort and sportiness,
ensuring a smooth ride even on less-than-perfect roads. Conclusion: The Ford Mustang GT in white is a perfect blend of beauty,
power, and sophistication. It's a car that not only performs exceptionally well but also turns heads wherever it goes.
Whether you're a long-time Mustang fan or new to the world of muscle cars, this vehicle will exceed your expectations.
Highly recommended for anyone looking for a thrilling and stylish driving experience.""",
"image": "images/car.jpg"
}
]

def Home(request):
return render(request, "home.html")

def SignUp(request):
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
form_info = UserRegister(
username=form.cleaned_data.get('username'),
email=form.cleaned_data.get('email'),
password=form.cleaned_data.get('password1')
)
form_info.save()
messages.success(request, 'Your account has been created!')
return HttpResponseRedirect('/Products')
else:
print("Form is not valid")
print(form.errors)
else:
form = UserRegisterForm()
return render(request, 'SignUp.html', {'form': form})

def Products(request):
return render(request, "products.html")

def about_product(request, slug):
for product in products:
if product["slug"] == str(slug):
return render(request, "about_product.html", {"product": product})
raise Http404("Product not found")

def Login(request):
if request.method == "POST":
form = UserLoginForm(request.POST)
print(form.is_bound)
if form.is_valid():
user = authenticate(
request,
username=form.cleaned_data.get('username'),
password=form.cleaned_data.get('password')
)
if user is not None:
login(request, user)
return HttpResponseRedirect('/Products')
else:
print("Form is not valid")
print(form.errors)
print(form.non_field_errors)
else:
form = UserLoginForm()
return render(request, "Login.html", {'form': form})

< /code>
urls.py

from django.urls import path
from . import views

urlpatterns=[path("Home",views.Home),
path("SignUp",views.SignUp,name='Signup'),
path("Products",views.Products,name="Products"),
path('Products/',views.about_product,name="About Product"),
path("Login",views.Login,name='Log')]

< /code>
login.html

{% extends "base.html" %}

{% block title %}
Login
{% endblock %}

{% load static %}

{% block css_files %}

{% endblock %}

{% block content %}

{% csrf_token %}

{% if form.non_field_errors %}

{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}

{% endif %}

Username
{{ form.username }}
{% if form.username.errors %}

{% for error in form.username.errors %}
{{ error }}
{% endfor %}

{% endif %}


Password
{{ form.password }}
{% if form.password.errors %}

{% for error in form.password.errors %}
{{ error }}
{% endfor %}

{% endif %}

Login


{% endblock %}

< /code>
terminal:-< /p>
false (print (form.is_bound))
форма не действительна < /p>
(print (form.non_field_error))

Подробнее здесь: https://stackoverflow.com/questions/794 ... redentials
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»