在扩展Django用户模型后创建新用户

时间:2016-06-24 17:05:00

标签: python django python-3.x

似乎无法找到明确回答我问题的回复。

如果使用以下基本代码扩展Django用户模型:

employee

这对创建新用户有何影响?创建新用户时是否自动创建department类对象?如果需要merge into字段,如何同时创建用户对象和员工对象?

2 个答案:

答案 0 :(得分:4)

如果您希望在创建应用实例或创建用户时,可以使用django信号,这将在创建新用户时自动创建实例。

models.py

from django.db.models.signals import *
from __future__ import unicode_literals

class Employee(models.Model):

    userName = models.OneToOneField(User, related_name='profile')
    department = models.CharField(max_length=100, null=True)

    def __unicode__(self):  # __str__
        return unicode(self.userName)

def create_user_profile(sender, instance, created, **kwargs):
    if created:
    Employee.objects.create(userName=instance)

post_save.connect(create_user_profile, sender=User)

这将在创建新用户时自动创建员工实例(之后可以添加空白实例数据)。

如果您希望扩展用户模型并希望在创建用户时添加更多信息,可以使用django-betterforms(http://django-betterforms.readthedocs.io/en/latest/multiform.html

models.py

from django.db.models.signals import *
from __future__ import unicode_literals

class Employee(models.Model):

    userName = models.OneToOneField(User, related_name='profile')
    department = models.CharField(max_length=100)

    def __unicode__(self):  # __str__
        return unicode(self.userName)

forms.py

from django import forms
from django.forms import ModelForm
from betterforms.multiform import MultiModelForm
from django.contrib.auth.forms import UserCreationForm
from .models import *

class EmployeeForm(ModelForm):

    class Meta:
        model = Employee
        exclude = ('userName',)


class addEmployeeMultiForm(MultiModelForm):
    form_classes = {
        'user':UserCreationForm,
        'profile':EmployeeForm,
    }

views.py

from django.views.generic import CreateView
from django.shortcuts import redirect
from .models import *
from .forms import *

class addEmployee(CreateView):
    form_class = addEmployeeMultiForm
    template_name = "addEmployee.html"
    success_url = '/your url after user created'

    def form_valid(self, form):
        user = form['user'].save()
        profile = form['profile'].save(commit=False)
        profile.userName = User.objects.get(username= user.username)
        profile.save()
        return redirect(self.success_url)

urls.py

from .views import *

           urlpatterns = [
                 url(r'^addemp/$', addEmployee.as_view(), name='addemp'),
           ]

addEmployee.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form action="." method="post">
            {% csrf_token %}
            {{ form }}     
            <button type="submit">Add</button>
        </form>
     </body>
</html>

答案 1 :(得分:2)

不会自动创建mediaPlaybackRequiresUserAction对象。要同时创建employee对象和user对象,可以使用employee实例

user