我正在尝试在我的视图中对以下内容进行硬编码以进行测试。如何在不遇到错误的情况下执行此操作?
我的观点:
play = form.save(commit=False)
play.track = 2
play.save()
request.user.message_set.create(message='Play Was created')
if 'next' in request.POST:
next = request.POST['next']
else:
next = reverse('coup_show')
return HttpResponseRedirect(next)
return render_to_response(
'dash/create.html',
{'form':form},
context_instance = RequestContext(request)`
我的模特:
class Play(models.Model):
track = models.ForeignKey(Track,null=True, related_name='track_creator_set')
当我尝试这个时,我收到以下错误......
Cannot assign "2": "Play.track" must be a "Track" instance.
答案 0 :(得分:2)
试试这个:
play.track = Track.objects.get(pk=2)
您需要指定Track模型的实例,而不仅仅是pk。
答案 1 :(得分:2)
您只想将其设置为跟踪2?
怎么样:
play.track = Track.objects.get(id=2)
错误告诉你,你试图给它一个数字,而实际上你需要一个Track,所以解决方案是给它一个Track。 :)