Django HardCoding Many to Many fields in a form
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开发者_如何学Go)
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.
Try this:
play.track = Track.objects.get(pk=2)
You need to assign an instance of the Track model, rather than just the pk.
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. :)
精彩评论