Django - 用户表单的额外字段 [英] Django - extra fields for user form

查看:122
本文介绍了Django - 用户表单的额外字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我开发的网站中,我有一个表单来注册扩展 userCreationForm 的用户。所述表单仅添加不属于默认值的字段,但它们位于模型中,例如电子邮件,first_name和last_name。

In the site I'm developing I have a form to register users that extends the userCreationForm. Said form only adds fields that are not in the default, but they are in the model such as email, first_name and last_name.

class RegisterForm(UserCreationForm):
    email = forms.EmailField(label = "Email", required=True)
    first_name = forms.CharField(label = "First name", required = True )
    last_name = forms.CharField(label = "Last name", required = True)

    class Meta:
        model = User
        fields = ("username", "first_name", "last_name", "email", "password1", "password2" )

    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)

        for fieldname in ['username', 'password1', 'password2']:
            self.fields[fieldname].help_text = None

我的问题是如果有一种方法可以添加另一个字段,如imagefield,出生日期等,以便我可以做出更完整的用户个人资料?或者我必须创建自己的用户模型?

My question is if there's a way to add another field like an imagefield, date of birth, etc. so that I can make a more complete user profile? Or do I have to create my own user model?

推荐答案

将Django惯用方式添加到User模型的更多字段是做一个第二个模型,其中 User 是一个 ForeignKey 。所以:

The Django idiomatic way of adding more fields to the User model is to make a second model where User is a ForeignKey. So:

from django.db import models
from django.contrib.auth.models import User

class MyUser(models.Model):
    user = models.ForeignKey(User)
    # ... other fields.  i.e. imagefield, date of birth (dob), etc ..
    # example:
    dob = models.DateField()

这篇关于Django - 用户表单的额外字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆