扩展用户模型Django

时间:2017-08-13 01:11:25

标签: django django-models django-forms

我正在尝试将每个用户与具有生物,位置和生日等信息的用户个人资料相关联。我希望这些字段与实际的User模型注册同时填写。

models.py:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

forms.py:

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

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required = True)

    class Meta:
        model = User #model User comes with username, email, first name, last name , pass1 and pass2 fields
        fields = (
            'username',
            'email',
            'first_name',
            'last_name',
            'password1',
            'password2'
        )

    def save(self, commit = True):
        user =  super(RegistrationForm, self).save(commit = False)
        user.first_name = self.cleaned_data['first_name']
        user.last_name =  self.cleaned_data['last_name']
        user.email =  self.cleaned_data['email']

        #note password is saved automatically in User models original save()
        # function, everything else needs to be done manually as done above
        if commit:
            user.save()

            return user

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('location','bio')

views.py

from django.shortcuts import render, redirect
from .forms import RegistrationForm,ProfileForm



def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if form.is_valid() and profile_form.is_valid():
            form.save()
            profile_form.save()
            return redirect('login')

    else:
        form = RegistrationForm()
        profile_form = ProfileForm()


    return render(request, 'accounts/register.html', {'form': form})

register.html

{%  extends 'accounts/base.html' %}

{% block head %}
    <title> Sign Up</title>
{% endblock %}
{% block body %}
  <h2>Sign up</h2>

  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    {{ profile_form.as_p }}
    <button type="submit">Sign up</button>
  </form>
{% endblock %}

当我进入/注册时,它仍会显示原始用户注册表单,其中包含User模型(usernameemailfirst_name附带的字段, last_namepassword),但UserProfile字段都没有,为什么会这样?

1 个答案:

答案 0 :(得分:0)

保存用户个人资料信息的正确方法是解决您的所有问题

from django.contrib.auth.base_user import AbstractBaseUser

class MyUser(AbstractBaseUser, PermissionsMixin):
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    phone = models.EmailField(_('email address'), unique=True)
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)

修改您的设置

AUTH_USER_MODEL = 'project.MyUser'

当你想获得你的MyUser模型时

from django.contrib.auth import get_user_model
MyUser = get_user_model()

现在,您在代码中执行所有操作以使其完美运行

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required = True)

    class Meta:
        model = MyUser
    fields = (
        'username',
        'bio',
        'birth_date',
        'avatar',
        'password1',
        'password2'
    )