Django注册额外的字段

问题描述 投票:0回答:1

我已经使用UserCreationForm扩展了我的SignUp表单并进行了电子邮件激活。所有的工作都很完美,但我不明白我是如何处理新变量的。我无法在模板中显示它,我在用户管理面板中找不到它。

forms.朋友

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

class SignUpForm(UserCreationForm):
    phone = forms.CharField(max_length= 20)   #<--my new variable 

    class Meta:
        model = User
        fields = ('phone', 'email', 'password1', 'password2',)

views.朋友

def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            mail_subject = 'Activate your blog account.'
            message = render_to_string('reg/acc_active_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid':urlsafe_base64_encode(force_bytes(user.pk)),
                'token':account_activation_token.make_token(user),
            })
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(
                        mail_subject, message, to=[to_email]
            )
            email.send()
            return HttpResponse('Please confirm your email address to complete the registration')
    else:
        form = SignUpForm()
    return render(request, 'reg/signup.html', {'form': form})


def activate(request, uidb64, token):
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)
        # return redirect('index')
        return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
    else:
        return HttpResponse('Activation link is invalid!')

如果我尝试在{{user.phone}}这样的html模板上插入手机,我看不到任何内容。如果我尝试在admin.py文件中添加手机,就像这样

admin.朋友

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
from django.utils.translation import ugettext_lazy as _
from .models import User

@admin.register(User)
class UserAdmin(DjangoUserAdmin):
    """Define admin model for custom User model with no email field."""

    fieldsets = (
        (None, {'fields': ('email', 'phone' ,'password',)}),
        (_('Personal info'), {'fields': ('first_name', 'last_name')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'password1', 'password2'),
        }),
    )
    list_display = ('email', 'first_name', 'last_name', 'is_staff')
    search_fields = ('email', 'first_name', 'last_name')
    ordering = ('email',)

出现错误

Unknown field(s) (phone) specified for User. Check fields/fieldsets/exclude attributes of class UserAdmin.

我的自定义用户模型

models.朋友

from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db import models
from django.utils.translation import ugettext_lazy as _


class UserManager(BaseUserManager):
    """Define a model manager for User model with no username field."""

    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """Create and save a User with the given email and password."""
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        """Create and save a regular User with the given email and password."""
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        """Create and save a SuperUser with the given email and password."""
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)

class User(AbstractUser):
    """User model."""

    username = None
    email = models.EmailField(_('email address'), unique=True)


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()
django
1个回答
1
投票

你需要了解Django中FormModel之间的区别。 Form(也是一个ModelForm)正如它所说的那样,是您向用户呈现的HTML表单的Django表示。它的唯一目的是通过POST请求轻松提交数据。

除非存在底层模型,否则表单不能只保存到数据库。使用普通的Form,您必须在处理POST请求的视图中执行此操作:

if request.method == 'POST':
    form = MyForm(data=request.POST)
    if form.is_valid():
        my_model = MyModel(param1=form.cleaned_data['param1'], ...)
        my_model.save()
        return redirect(success_url)
    ...

如您所见,模型和表单都必须具有相应的字段(在上面的示例中,param1等等)。

为了更容易为模型创建表单,Django为您提供了ModelForm,其中表单“知道”如何保存底层模型,因此您可以:

if request.method == 'POST':
    form = MyModelForm(data=request.POST)
    if form.is_valid():
        my_model = form.save()
        ...

在这种情况下,表单将表单字段映射到模型字段,因此只能保存模型上存在的那些模型字段。您的表单可能包含5个未在模型上定义的额外字段,仍然可以验证,但保存表单时这些字段没有任何反应,因为模型没有它们。

完整的文档是here

© www.soinside.com 2019 - 2024. All rights reserved.