无法将值(用户标识)分配给ForeignKey字段
我收到以下错误: 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
这是我的views.py的一部分:
from django.db import models from django.shortcuts import render_to_response, redirect, get_object_or_404 from django.template import RequestContext from django.contrib.auth.models import User from holaProy.models import UserForm, Worry, WorryForm, Statistics, StatisticsForm def worry_add (request): form = WorryForm (request.POST or None) if form.is_valid(): wform.user = models.ForeignKey('User') #HERE IS THE PROBLEM I THINK wform.save() return redirect (index) return render_to_response ('holaProy/worry_add.html', {'worry_form': form}, context_instance = RequestContext(request))</code>
我应该怎么做才能成功地将当前用户标识分配给实际担心实例的“用户”字段?
问题的确在于此:
wform.user = models.ForeignKey('User')
wform.user
应该被设置为一个User
实例。 像这样的东西:
user = request.user # Retrieve proper user according to your needs
wform.user = user
尝试:
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()
这是你遇到问题的地方。
基本上,你正在寻找一个字符串。 你需要先获得实际的数据库对象。 尝试这个:
User = User.objects.get(pk='User')
wform.user = models.ForeignKey('User') #Now User refers to the database object, not a string
链接地址: http://www.djcxy.com/p/9677.html
上一篇: Can't assign a value (user id) to a ForeignKey field
下一篇: csrf token Follow up