无法将值(用户标识)分配给ForeignKey字段

时间:2012-11-27 20:25:43

标签: python django django-models

我收到以下错误: Cannot assign "<django.db.models.fields.related.ForeignKey>": "Worry.user" must be a "User" instance.

我尝试将当前用户的id分配给我刚刚创建的对象。

这是我的models.py:

的一部分

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

    class UserForm (ModelForm) :  
        class Meta:  
            model = User        
    class Worry(models.Model) :    
        user = models.ForeignKey(User) #Many worries to 1 user relation

This is part of my views.py:

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

    class UserForm (ModelForm) :  
        class Meta:  
            model = User        
    class Worry(models.Model) :    
        user = models.ForeignKey(User) #Many worries to 1 user relation

如何将当前用户ID成功分配给实际忧虑实例的“用户”字段?

3 个答案:

答案 0 :(得分:4)

问题确实存在于那条线上:

wform.user = models.ForeignKey('User')

wform.user应设置为User个实例。像这样:

user = request.user    # Retrieve proper user according to your needs
wform.user = user

答案 1 :(得分:0)

尝试:

def worry_add(request):
    form = WorryForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        worry = form.save(commit=False)
        worry.user = #assign this to an instance of a User object
        worry.save()

答案 2 :(得分:0)

这就是你遇到问题的路线。

基本上,您正在搜索字符串。您需要先获取实际的数据库对象。 试试这个:

User = User.objects.get(pk='User')
wform.user = models.ForeignKey('User')  #Now User refers to the database object, not a string