2014-04-03 225 views
2

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

然后下面是我创建的两个模型。

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

简单的答案是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类来处理此问题。 Form类将允许您以更简单的方式处理大量这些东西,并提供一些非常需要的验证方法。您可以在此查看相关文件:https://docs.djangoproject.com/en/1.6/topics/forms/