Django 密码更改视图

问题描述 投票:0回答:2

我正在尝试使用我自己的模板和表单在我的 django 应用程序中实现密码更改。所以我决定创建自己的视图函数而不是使用 django 的。我遇到的问题是更改密码页面不会更改密码。我的表单刚刚重新加载并显示一个错误“出了问题”,您可以在我的 chgpwd.html 模板中看到它来自的 if 语句。我不确定是否还有其他方法可以在此模板上实现错误,但这就是它向我展示的全部内容。奇怪的是,我对 django 提供的表单使用了相同的视图,它可以工作,但是一旦我插入我的模板和表单,它就停止工作。我不知道我的问题是什么,确实需要一些帮助,谢谢。

chgpwd.html 模板

{%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%}

网址.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(user=request.user, request.POST)
        if form.is_valid():
            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})

表格.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
python django django-views django-forms django-templates
2个回答
1
投票

form.is_valid()函数需要一个带有“name”属性=“old_password”的输入字段。如果它找不到它,因为就像您的情况一样,“name”属性不同(“oldPwd”),则验证失败。 我不知道新密码和新密码确认字段是否也是如此; Django 的表单名称分别为“new_password1”和“new_password2”。


0
投票

如果你想在不使用 django 表单而是使用 html 传统表单的情况下实现更改密码,你可以按照我在这里放置的方法进行操作。

views.py

from django.views import generic
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.mixins import LoginRequiredMixin

class ChangePasswordView(LoginRequiredMixin, generic.TemplateView):
    template_name = 'users/change_password.html'
    success_url = reverse_lazy("user_profile")

    def post(self, request, *args, **kwargs):
        old_password: str = request.POST.get("old_password")
        new_password1: str = request.POST.get('new_password1')
        new_password2: str = request.POST.get('new_password2')

        user: CustomUser = request.user

        if not user.check_password(old_password):
            messages.warning(request, "old password doesn't match.")
            return redirect("change_password")

        if len(new_password1) < 10:
            messages.warning(request, "password length should not be less than 10.")
            return redirect("change_password")

        if old_password == new_password1:
            messages.warning(request, "your new password cannot be the same as your old password.")
            return redirect("change_password")

        if new_password1 != new_password2:
            messages.warning(request, "new_password1 and new_password2 do not match.")
            return redirect("change_password")

        user.set_password(new_password1)
        user.save()
        update_session_auth_hash(request, user)
        messages.success(request, "password change successfull. your new password would take effect on next login.")
        return redirect("user_profile")
```
This is tested and confirmed working with django 4.2.7.
© www.soinside.com 2019 - 2024. All rights reserved.