password1 和 password2 不以 django 形式保存

password1 and password2 doesn't save in django form

我创建了一个如下所示的 (CustomUserForm):

from django.contrib.auth.forms import UserChangeForm
from .models import User
from django import forms


class CustomUserForm(UserChangeForm):
    username = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter Username'}))
    email = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter The Email'}))
    password1 = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter The Password'}))
    password2 = forms.CharField(
        widget=forms.PasswordInput(attrs={'class': 'form-control my-2', 'placeholder': 'Confirm Password'}))

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

以及创建新用户对应的视图:

from django.shortcuts import render, redirect
from django.contrib import messages
from store.forms import CustomUserForm


def register(request, self):
    form = CustomUserForm()
    if request.method == 'POST':
        form = CustomUserForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, "Registered Successfully")
            return redirect('/login')
    context = {'form': form}
    return render(request, 'auth/register.html', context)


def login_page(request):
    return render(request, 'auth/login.html')

这是 register.html

{% extends 'layouts/main.html' %}
{% block title %} {{ category }} {% endblock %}
{% block content %}


    <section class="vh-100" style="background-color: #eee;">
  <div class="container h-100">
    <div class="row d-flex justify-content-center align-items-center h-100">
      <div class="col-lg-12 col-xl-11">
        <div class="card text-black" style="border-radius: 25px;">
          <div class="card-body p-md-5">
            <div class="row justify-content-center">
              <div class="col-md-10 col-lg-6 col-xl-5 order-2 order-lg-1">

                <p class="text-center h1 fw-bold mb-5 mx-1 mx-md-4 mt-4">Sign up</p>

                <form class="mx-1 mx-md-4" action="" method="POST">
                  {% csrf_token %}
                  <div class="d-flex flex-row align-items-center mb-4">
                    <i class="fas fa-user fa-lg me-3 fa-fw"></i>
                    <div class="form-outline flex-fill mb-0">
                      <label class="form-label" for="form3Example1c">Your Name</label>
                        {{ form.username }}
                        {% if form.errors.username %}
                            <span class="bg-danger text-danger">{{ form.errors.username }}</span>
                        {% endif %}
                    </div>
                  </div>

                  <div class="d-flex flex-row align-items-center mb-4">
                    <i class="fas fa-envelope fa-lg me-3 fa-fw"></i>
                    <div class="form-outline flex-fill mb-0">
                      <label class="form-label" for="form3Example3c">Your Email</label>
                        {{ form.email }}
                        {% if form.errors.email %}
                            <span class="bg-danger text-white">{{ form.errors.email }}</span>
                        {% endif %}
                    </div>
                  </div>

                  <div class="d-flex flex-row align-items-center mb-4">
                    <i class="fas fa-lock fa-lg me-3 fa-fw"></i>
                    <div class="form-outline flex-fill mb-0">
                      <label class="form-label" for="form3Example4c">Password</label>
                        {{ form.password1 }}
                        {% if form.errors.password1 %}
                            <span class="bg-danger text-danger">{{ form.errors.password1 }}</span>
                        {% endif %}
                    </div>
                  </div>

                  <div class="d-flex flex-row align-items-center mb-4">
                    <i class="fas fa-key fa-lg me-3 fa-fw"></i>
                    <div class="form-outline flex-fill mb-0">
                      <label class="form-label" for="form3Example4cd">Repeat your password</label>
                        {{ form.password2 }}
                        {% if form.errors.password2 %}
                            <span class="bg-danger text-danger">{{ form.errors.password2 }}</span>
                        {% endif %}
                    </div>
                  </div>

                  <div class="form-check d-flex justify-content-center mb-5">
                    <input class="form-check-input me-2" type="checkbox" value="" id="form2Example3c" />
                    <label class="form-check-label" for="form2Example3">
                      I agree all statements in <a href="#!">Terms of service</a>
                    </label>
                  </div>

                  <div class="d-flex justify-content-center mx-4 mb-3 mb-lg-4">
                    <button type="submit" class="btn btn-primary btn-lg">Register</button>
                  </div>

                </form>

              </div>
              <div class="col-md-10 col-lg-6 col-xl-7 d-flex align-items-center order-1 order-lg-2">

                <img src="https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-registration/draw1.webp"
                  class="img-fluid" alt="Sample image">

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

{% endblock %}

一切正常,除了在 MySQL 数据库中没有创建密码!!

我认为,密码需要正确散列,因为 django 不存储原始密码。

您可以使用 cleaned_data,并且您需要正确散列密码,因此您可以使用 from django.contrib.auth.hashers import make_password 中的 make_password()

因此,使用您当前的代码在 views.py 中进行以下修改。

from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password

def register(request, self):
    if request.method == 'POST':
        form = CustomUserForm(request.POST)
        if form.is_valid():
            username=form.cleaned_data['username']
            email=form.cleaned_data['email']
            password=make_password(form.cleaned_data['password1'])
            data=User(username=username,email=email,password=password)
            data.save()            
            messages.success(request, "Registered Successfully")
            return redirect('/login/')
    else: #Here GET condition
        form = CustomUserForm()
    context = {'form': form}
    return render(request, 'auth/register.html', context)

Note: You must give / at the end of every route.