【问题标题】:django custom user model form widgets working only for email and name fielddjango 自定义用户模型表单小部件仅适用于电子邮件和姓名字段
【发布时间】:2020-09-14 22:05:00
【问题描述】:

在我使用 AbstractBaseUser 创建的自定义用户模型中,当我尝试添加允许我添加类或占位符或输入类型等的小部件时。它仅适用于全名和电子邮件字段,但不适用于密码 1 和密码 2

在我的models.py中

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.conf import settings


class MyAccountManager(BaseUserManager):
    def create_user(self, email, full_name, password=None):
        if not email:
            raise ValueError('Users must have an email address')
        if not full_name:
            raise ValueError('Users must have a name')

        user = self.model(
            email=self.normalize_email(email),
            full_name=full_name,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, full_name, password):
        user = self.create_user(
            email=self.normalize_email(email),
            full_name=full_name,
            password=password,
        )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user


class User(AbstractBaseUser):
    email = models.EmailField(verbose_name="Email",max_length=250, unique=True)
    username = models.CharField(max_length=30, unique=True, null=True)
    date_joined = models.DateTimeField(verbose_name='Date joined', auto_now_add=True)
    last_login = models.DateTimeField(verbose_name='Last login', auto_now=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    full_name = models.CharField(verbose_name="Full name", max_length=150, null=True)
    profile_pic = models.ImageField(null=True, blank=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['full_name']

    objects = MyAccountManager()

    def __str__(self):
        return self.full_name

    # For checking permissions.
    def has_perm(self, perm, obj=None):
        return self.is_admin

    # For which users are able to view the app (everyone is)
    def has_module_perms(self, app_label):
        return True

#i also have another text model which i don't think that is needed  

在我的 forms.py 中

from django.forms import ModelForm
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate
from .models import *


class TextForm(ModelForm):
    class Meta:
        model = Text
        fields = ['title','document','requirements','deadline']
        widgets = {
            'title' : forms.TextInput(attrs={'placeholder':'Title','class':'form-control m-2 mb-4 pb-2'}),
            'deadline' : forms.DateInput(attrs={'placeholder':'Deadline','type':'date','class':'form-control m-2 pt-2',
            'id':'opendate'}),
            'requirements' : forms.Textarea(attrs={'placeholder':'requirements','class':'form-control col m-2','rows':'3'}),
            'document' : forms.Textarea(attrs={'placeholder':'document','class':'form-control'}),

        }

class SignupForm(UserCreationForm):

    class Meta:
        model = User 
        fields = ("full_name","email","password1","password2")
        widgets = {
            'full_name' : forms.TextInput(attrs={'placeholder':'Full name'}),
            'email' : forms.EmailInput(attrs={'placeholder':'Email'}),
            'password1' : forms.PasswordInput(attrs={'placeholder':'Password'}),
            'password2' : forms.PasswordInput(attrs={'placeholder':'Password2'}),

        }


class SigninForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ('email','password')
        widgets = {
            'email' : forms.EmailInput(attrs={'placeholder':'Email','class':'form-control'}),
            'password' : forms.PasswordInput(attrs={'placeholder':'Password','class':'form-control'}),

        }

    def clean(self):
        if self.is_valid():
            email = self.cleaned_data['email']
            password = self.cleaned_data['password']
            if not authenticate(email=email,password=password):
                raise forms.ValidationError("Invalid login")

在我的 view.py 文件中

def home(request):

    user = request.user

    # for creating posts

    form = TextForm()

    if request.method == "POST":
        form = TextForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            author = User.objects.filter(email=user.email).first()
            obj.author = author
            form.save()
            form = TextForm()

    texts = Text.objects.all().order_by('-id')

    # for signing in

    if request.POST:
        signin_form = SigninForm(request.POST)
        if signin_form.is_valid():
            email = request.POST['email']
            password = request.POST['password']
            user = authenticate(email=email, password=password)
            if user:
                login(request, user)
    else:
        signin_form = SigninForm()
    
    # for signing up

        signup_form = SignupForm()
    if request.method == 'POST':
        signup_form = SignupForm(request.POST)
        if signup_form.is_valid():
            User = signup_form.save()
            full_name = signup_form.cleaned_data.get('full_name')
            email = signup_form.cleaned_data.get('email')
            raw_password = signup_form.cleaned_data.get('password1')
            account = authenticate(email=email, password=raw_password)
            login(request, account)

    context = {'signin_form':signin_form,'signup_form':signup_form,'form': form, 'texts': texts}

    return render(request, 'main/home.html', context)

注意:在模板中,我将它们一一渲染,例如: {{signup_form.full_name}} 、 {{signup_form.password1}} 等...并且在后端方面工作正常

【问题讨论】:

  • 试试这个:forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))
  • @itjuba 成功了
  • 来自 Dz Dev ,对你有好处。
  • 哦是的酷..

标签: python django django-models django-forms django-templates


【解决方案1】:

当您使用from django.contrib.auth.forms import UserCreationForm 时,您应该使用“__init__”函数,例如:

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

class SignUpForm(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField(max_length=255)
last_name = forms.CharField(max_length=255)

class Meta:
    model = User
    fields = ('username', 'first_name', 'last_name',
              'email', 'password1', 'password2')
def __init__(self, *args, **kwargs):
    super(SignUpForm, self).__init__(*args, **kwargs)
    self.fields["username"].widget.attrs['class'] = 'form-control'
    self.fields["first_name"].widget.attrs['class'] = 'form-control'
    self.fields["last_name"].widget.attrs['class'] = 'form-control'
    self.fields["email"].widget.attrs['class'] = 'form-control'
    self.fields["password1"].widget.attrs['class'] = 'form-control'
    self.fields["password2"].widget.attrs['class'] = 'form-control'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-02
    • 2023-03-09
    • 2013-03-13
    • 2020-12-31
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2014-12-12
    相关资源
    最近更新 更多