#python #django #django-models #django-forms #django-templates
#python #django #django-модели #django-forms #django-шаблоны
Вопрос:
в моей пользовательской модели пользователя, созданной с помощью AbstractBaseUser, когда я пытаюсь добавить виджеты, которые позволяют мне добавлять классы или заполнители или тип ввода и т. Д., Это работает только для полей full_name и email, но не для password1 и password2
в моем 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}} и т. Д. … И он отлично работает с точки зрения серверной части
Комментарии:
1. Попробуйте это: формы. CharField(виджет = формы. PasswordInput(attrs={‘заполнитель’: ‘Пароль’}))
2. @itjuba спасибо, что это сработало
3. От Dz Dev, молодец, приятель.
4. о, да, круто..