[英]How can i add extra model fields to default auth_user model using django
[英]How to add fields with default values to the User model in Django
我需要向用戶 model 添加字段,默認值不會顯示在注冊表單中,但我是 Django 的新手。 我該如何實施它,我做錯了什么? 模型.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
level = models.IntegerField(default=0)
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')
視圖.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'
設置.py:
AUTH_USER_MODEL = 'users.CustomUser'
如果您只想使用占位符,只需從 model 中刪除默認值,因為表單中的值會取代占位符。
如果這不是一個選項,那么您可以在表單字段中定義一個初始參數
這是一個例子:
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.