Представление изменения пароля в Django
Я пытаюсь реализовать смену пароля в моем приложении django, с моим собственным шаблоном и формой. Поэтому я решил создать свою собственную функцию представления вместо того, чтобы использовать функцию django. Проблема в том, что страница смены пароля не меняет пароль. Я не могу понять, в чем моя проблема, и мне очень нужна помощь, спасибо.
chgpwd.html template
{%extends 'auth_base.html'%}
{%load static%}
{%block title%} CX Labs SOC LogIn {% endblock%}
{%block content%}
<div class="wrapper" style="max-width:450px">
{%if form.errors %}
<p style="text-align:center; margin-bottom:30px; color:red;">something went wrong</p>
{%endif%}
<div class="logo"> <img src="{%static 'website/cxlabs.jpg'%}" alt=""> </div>
<div class="text-center mt-4 name"> CXLabs SOC <br/> Password Change</div>
<form method="post" class="p-3 mt-3">
<div class="form-field d-flex align-items-center"> <span class="far fa-user"></span> {{form.oldPwd}} </div>
<div class="form-field d-flex align-items-center"> <span class="far fa-user"></span> {{form.newPwd1}} </div>
<div class="form-field d-flex align-items-center"> <span class="fas fa-key"></span> {{form.newPwd2}} </div> <button type="submit" class="btn mt-3">Change Password</button>
{%csrf_token%}
</form>
</div>
{%endblock%}
Urls.py
import django
from django.contrib import admin
from django.contrib.auth import views as av
from django.urls import path, include
from authentication.forms import CustomAuthForm, CustomPwdChgForm
from website import views
from authentication import views as authv
urlpatterns = [
path('logout/', av.LogoutView.as_view(template_name='registration/logout.html',
next_page=None), name='logout'),
path('chgpwd/', authv.changepwview, name='chgpwd'),
path('sign/', include('sign.urls')),
path('download/<int:id>', views.zip_download, name='zipDL')
]
views.py
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, update_session_auth_hash
from django.contrib.auth.views import PasswordChangeView
from authentication.forms import CustomPwdChgForm
from django.urls import reverse_lazy
from website import views
from django.apps import apps
# Create your views here.
def changepwview(request):
if request.method == 'POST':
form = CustomPwdChgForm(request.user, request.POST)
if form.is_valid():
user = form.save()
update_session_auth_hash(request, user)
# messages.success(request,
# 'Your password was successfully updated!',
# extra_tags='alert-success')
return redirect('home')
else:
form = CustomPwdChgForm(user=request.user)
return render(request, 'registration/chgpwd.html', {'form': form})
forms.py
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
from django.forms.widgets import PasswordInput, TextInput
class CustomAuthForm(AuthenticationForm):
username = forms.CharField(widget=TextInput(
attrs={'placeholder': 'Username'}))
password = forms.CharField(widget=PasswordInput(
attrs={'placeholder': 'Password'}))
class CustomPwdChgForm(PasswordChangeForm):
oldPwd = forms.CharField(widget=TextInput(
attrs={'placeholder': 'Old Password'}))
newPwd1 = forms.CharField(widget=TextInput(
attrs={'placeholder': 'New Password'}))
newPwd2 = forms.CharField(widget=TextInput(
attrs={'placeholder': 'New Password'}))
class meta:
model = User
Функция form.is_valid () ожидает наличия поля ввода с атрибутом "name" = "old_password". Если она не находит его, потому что, как в вашем случае, атрибут "name" другой ("oldPwd"), валидация не проходит. Я не знаю, относится ли то же самое к полям подтверждения нового пароля и нового пароля; в Django имена форм - "new_password1" и "new_password2" соответственно.