Django-如何使用CreateView扩展自定义用户

时间:2019-04-22 07:47:24

标签: django

我想使用CreateView创建用户注册表单。但是,我不知道如何在view.py中将用户模型与配置文件模型结合起来

我的环境 ・ Django2.2

这是我写的代码:

■️model.py

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    gender = models.CharField(max_length=20, blank=True)

■️form.py

class UserCreateForm(UserCreationForm):

    class Meta:
        model = User
        if User.USERNAME_FIELD == 'email':
            fields = ('email',)
        else:
            fields = ('username', 'email')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['class'] = 'form-control'

class ProfileForm(forms.ModelForm):
    CHOICES = (
        ('female', 0,),
        ('male', 1,),
        ('not_applicable', 2,)
    )
    gender = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES, required=False)

▪️View.py

from django.views import generic
from .forms import UserCreateForm

class UserCreate(generic.CreateView):
    template_name = 'accounts/create.html'
    form_class = UserCreateForm

    def form_valid(self, form):
        user = form.save(commit=False)
        user.is_active = False
        user.save()

        current_site = get_current_site(self.request)
        domain = current_site.domain
        context = {
            'protocol': 'https' if self.request.is_secure() else 'http',
            'domain': domain,
            'token': dumps(user.pk),
            'user': user,
        }

        subject_template = get_template('accounts/mail/create/subject.txt')
        subject = subject_template.render(context)

        message_template = get_template('accounts/mail/create/message.txt')
        message = message_template.render(context)

        user.email_user(subject, message)
        return redirect('accounts:user_create_done')

▪️create.html

<form action="" method="POST">
    {{ form.non_field_errors }}
            {% for field in form %}
                    <p>{{ field }} {{ field.errors }}</p>
            {% endfor %}
    {% csrf_token %}
    <button type="submit" class="button-submit">submit</button>
</form>

但是,它只能显示“用户列”(仅电子邮件,密码)。但我想显示“用户栏”和“个人资料栏”(电子邮件,密码,名字,姓氏,性别)。

这可能吗?

2 个答案:

答案 0 :(得分:0)

您应该在自己的AbstractBaseUser中继承CustomUserModel,添加所需的其他字段,然后在AUTH_USER_MODEL=yourapp.CustomUserModel文件中覆盖settings.py

还有可能值得一看this

答案 1 :(得分:0)

fields的{​​{1}}中的Meta列表应包含您需要显示的所有字段。您还应该在UserCreationForm中添加配置文件字段,并手动更新配置文件。另外,请更改表单的名称以使其与django的UserCreationFrom区别开来。

此外,请确保每次致电UserCreateForm时,都会为该用户创建一个个人资料。

user.profile

更新您的表单。

# models.py
# add the below line in the end of the file.
User.profile = property(lambda u: Profile.objects.get_or_create(user=u)[0])

在您看来,您可以将# forms.py class CustomUserCreateForm(UserCreationForm): CHOICES = ( ('female', 0,), ('male', 1,), ('not_applicable', 2,) ) gender = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES, required=False) class Meta: model = User if User.USERNAME_FIELD == 'email': fields = ('email',) else: fields = ('username', 'email') fields += ('password', 'first_name', 'last_name', 'gender') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' 的值保存在gender中。

user.profile