使用与默认用户模型具有外键关系的Django模型

时间:2014-04-03 19:48:35

标签: django django-models foreign-keys django-views django-users

我正在编写一个Django程序,其中Department / Position字段与User模型相关联。在注册页面上,一个人需要输入姓/名,电子邮件,用户名,密码,这些是默认的用户模型字段,以及他们的部门和职位。

接下来是我创建的两个模型。

class Department(models.Model):
    department_id = models.AutoField(primary_key=True)
    department_name = models.CharField(max_length=100, unique=True)
    is_active = models.BooleanField(default=True)

class Position(models.Model):
    position_id = models.AutoField(primary_key=True)
    position_name = models.CharField(max_length=100)
    department = models.ForeignKey(Department)
    user = models.OneToOneField(User, blank=True, related_name="position")

在views.py中,关联的视图如下所示:

def sign_up_in(request):
    global user
    post = request.POST
    if post['email'] is u'' or post['password'] is u'':
        msg = 'Please check sign-up input forms'
        return render_to_response('none.html', {'msg': msg})
    else:
        if not user_exists(post['email']):
            user = create_user(username=post['email'], email=post['email'], password=post['password'])
        user.first_name=post['first']
        user.last_name=post['last']
        **user.position.position_name=post['position']**
        user.department=post['department']
        user.is_staff = True
        user.save()

        msg = 'Sign Up OK    ' + user.first_name + '  ' + user.last_name
    else:
        msg = 'Existing User'
    return render_to_response('login.html', {'msg': msg})

当我在上面的views.py中添加粗体线时,我开始收到错误“没有提供异常”。我应该在模型和视图中更改什么? 此外,在这行代码中,user = create_user(username = post ['email'],email = post ['email'],password = post ['password']),我该如何表达外键关系?

1 个答案:

答案 0 :(得分:1)

简单的答案是user.position尚不存在。

让我们将其分解以使其发挥作用。

def sign_up_in(request):
    ...
    post = request.POST
    ... # Your if block

        # 1. Create your user.
        user = User.objects.create_user(post['email'], post['email'], post['password'])
        user.first_name = post['first']
        user.last_name = post['last']
        user.is_staff = True
        user.save()
        # 2. Create/get your department.
        dept, created = Department.objects.get_or_create(department_name=post['department'])
        # 3. Create your position
        position = Position.objects.create(department=dept, user=user, position=post['position'])
    ...

请注意,User.objects.create_user()Foo.objects.create()会自动保存对象,因此如果您添加更多数据,则只需再次保存(如上面的用户所示)。

作为附注,虽然这将解决您遇到的问题,但我建议您废弃此特定视图并使用Form类来处理此问题。表单类将允许您以更简单的方式处理大量此类内容,并提供一些非常需要的验证方法。您可以在此处查看相关文档:https://docs.djangoproject.com/en/1.6/topics/forms/