[英]How to add fields with default values to the User model in Django
I need to add fields to the User model with default values that will not be displayed in the registration form but I am new to Django.我需要向用户 model 添加字段,默认值不会显示在注册表单中,但我是 Django 的新手。 How can I implement it and what am I doing wrong?我该如何实施它,我做错了什么? models.py:模型.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
level = models.IntegerField(default=0)
forms.py: forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from .models import CustomUser
class RegisterUserForm(UserCreationForm):
username = forms.CharField(label="Имя", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input',
'placeholder': 'введите ваше имя'}))
email = forms.CharField(label="Почта", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-control',
'placeholder': 'введите вашу почту'}))
password1 = forms.CharField(label="Пароль", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input',
'placeholder': 'введите пароль'}))
password2 = forms.CharField(label="Подтверждение пароля", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input',
'placeholder': 'подтвердите ваш пароль'}))
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
for field_name in ['username', 'email', 'password1', 'password2']:
self.fields[field_name].help_text = None
class Meta:
model = CustomUser
fields = ('username', 'email', 'password1', 'password2')
views.py:视图.py:
from django.contrib.auth import logout
from django.contrib.auth.views import LoginView
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import RegisterUserForm, LoginUserForm
class RegisterUser(CreateView):
form_class = RegisterUserForm
success_url = reverse_lazy('login')
template_name = 'users/register.html'
settings.py:设置.py:
AUTH_USER_MODEL = 'users.CustomUser'
If you want to use only placeholder just remove the default value from model, since a value in a form takes presence over the placeholder.如果您只想使用占位符,只需从 model 中删除默认值,因为表单中的值会取代占位符。
If that is not an option then you can define an initial parameter in the form field如果这不是一个选项,那么您可以在表单字段中定义一个初始参数
Here is an example:这是一个例子:
class NewSomeModel(forms.ModelForm):
title = forms.CharField(
initial=None,
widget=forms.TextInput(attrs={'placeholder': 'Myplaceholdertext'})
)
def clean_title(self):
title = self.cleaned_data['title']
return title or 'some-default-value-here'
class Meta:
model = SomeModel
fields = ['title']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.