Django 对表单中的多对多字段进行硬编码
在我看来,出于测试目的,我正在尝试对以下内容进行硬编码。我该如何执行此操作而不遇到错误?
我的观点:
`def create(request): form= PlayForm(request.POST 或 None) if form.is_valid():
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.
I am trying to hardcode the following in my view for testing purposes. How do I do this without encountering an error?
My view:
`def create(request):
form= PlayForm(request.POST or None)
if form.is_valid():
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)`
My model:
class Play(models.Model):
track = models.ForeignKey(Track,null=True, related_name='track_creator_set')
When I try this I get the following error...
Cannot assign "2": "Play.track" must be a "Track" instance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
您需要分配 Track 模型的一个实例,而不仅仅是 pk。
Try this:
You need to assign an instance of the Track model, rather than just the pk.
您只想将其设置为轨道 2?
怎么样:
错误告诉您您正在尝试给它一个编号,而实际上您需要一个 Track,因此解决方案是给它一个 Track。 :)
You just want to set it to track 2?
How about:
The error is telling you that you're trying to give it a number, when in fact you need a Track, so the solution is to give it a Track. :)