在为模型创建记录时创建django用户

时间:2017-08-18 09:55:37

标签: python django django-models

models.py如下,

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

class members(models.Model):

    auto_id = models.AutoField(primary_key=True)
    member_name = models.OneToOneField(User)
    owner = models.ForeignKey('auth.User', related_name='webapi', on_delete=models.CASCADE)
    father_name = models.CharField(max_length=25, blank=False, default='')
    wife_name = models.CharField(max_length=25, blank=False, default='')
    number_of_child = models.IntegerField(blank=True)
    address_line_1 = models.CharField(max_length=40, blank=False, default='')
    address_line_2 = models.CharField(max_length=40, blank=True, default='')
    city = models.CharField(max_length=25, blank=False, default='')

    class Meta:
        ordering = ('member_name',)

现在上面已经与django auth Users表链接了,在steriliser中它显示了现有的Django用户,我必须在提交期间选择一个。

但我的要求是作为我登录的管理员用户,然后手动提供member_name,这也应该自动创建一个django用户

1 个答案:

答案 0 :(得分:0)

django-annoying有一个功能,特别是AutoOneToOneField

来自他们的github的样本:

from annoying.fields import AutoOneToOneField

class MyProfile(models.Model):
    user = AutoOneToOneField(User, primary_key=True)

这应该会自动创建一个用户。