簡體   English   中英

我可以通過 CBV 創建用戶實例而不是先創建表單嗎? (姜戈)

[英]Am I able to create a User instance by CBV rather than create a form first? (Django)

現在我使用 forms.py、models.py、views.py 來創建一個用戶實例,如下所示,它可以工作:

模型.py:

from django.db import models
from django.contrib import auth
from django.utils import timezone

# Create your models here.
class User(auth.models.User, auth.models.PermissionsMixin):

    def __str__(self):
        return "@{}".format(self.username)

視圖.py:

from django.shortcuts import render
from django.views import generic
from django.urls import reverse,reverse_lazy
from . import forms, models
from django.contrib.auth import get_user_model
# Create your views here.


class SignUp(generic.CreateView):
    form_class = forms.UserCreateForm
    success_url = reverse_lazy("login")
    template_name = "accounts/signup.html"

forms.py

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm


class UserCreateForm(UserCreationForm):
    class Meta:
        fields = ("username", "email", "password1", "password2")
        model = get_user_model()
# below code is not necessary, just want to customize the builtin attribtue of
# the User class
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["username"].label = "Display name"
        self.fields["email"].label = "Email address"

但是,我想知道是否可以通過編輯views.py 來創建用戶,如下所示。 視圖.py:

from django.shortcuts import render
from django.views import generic
from django.urls import reverse,reverse_lazy
from . import forms, models
from django.contrib.auth import get_user_model
# Create your views here.


class SignUp(generic.CreateView):
    model = get_user_model()
    success_url = reverse_lazy("login")
    template_name = "accounts/signup.html"
    fields = ("username", "email","password1","password2")



# below is original version
# class SignUp(generic.CreateView):
#     form_class = forms.UserCreateForm
#     success_url = reverse_lazy("login")
#     template_name = "accounts/signup.html"

當我在為用戶指定的“accounts/signup.html”未知字段(password1)(password2)中時出現錯誤。

如果我刪除這兩個字段“password1”、“password2”,我將能夠訪問“accounts/signup.html”並創建一個沒有密碼的用戶實例,盡管它沒有用,但我可以在管理頁面中看到它。

所以我想如果有什么好方法可以只使用 generic.Createview 和 User model 創建用戶?

為什么我會收到錯誤 Unknown field(s) (password1) (password2 )specified for User?

期待盡快得到任何建議!

UserCreationForm負責檢查password1 == password2 ,然后對密碼進行哈希處理並設置user.password

如果您沒有自定義表單,則不能使用password1password2 ,因為這些不是 model 字段。

您可以將password添加到視圖中的fields ,但它不會顯示為密碼輸入。 您還需要在視圖中添加代碼到 hash 保存用戶時的密碼。

因此,可以從SignUp中刪除表單,但我不建議這樣做,因為它會使視圖更加復雜,並且可能會失去功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM