2014-04-03 157 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/