Django 对表单中的多对多字段进行硬编码

发布于 2024-11-06 04:15:04 字数 849 浏览 0 评论 0原文

在我看来,出于测试目的,我正在尝试对以下内容进行硬编码。我该如何执行此操作而不遇到错误?

我的观点:

`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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怀念你的温柔 2024-11-13 04:15:04

试试这个:

play.track = Track.objects.get(pk=2)

您需要分配 Track 模型的一个实例,而不仅仅是 pk。

Try this:

play.track = Track.objects.get(pk=2)

You need to assign an instance of the Track model, rather than just the pk.

梦归所梦 2024-11-13 04:15:04

您只想将其设置为轨道 2?

怎么样:

play.track = Track.objects.get(id=2)

错误告诉您您正在尝试给它一个编号,而实际上您需要一个 Track,因此解决方案是给它一个 Track。 :)

You just want to set it to track 2?

How about:

play.track = Track.objects.get(id=2)

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. :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文