以下是views.py
中的赌博视图def gambling(request, profile_id):
Profile = get_object_or_404(profile, pk=profile_id)
coin = get_object_or_404(Coin, pk=profile_id)
try:
selected_choice = coin.Face.get(pk=request.POST['name'])
except (KeyError, Coin.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'gamble/detail.html', {
'Profile': Profile,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.Face
selected_choice.save()
return HttpResponseRedirect(reverse('gamble:results', args=(profile.id,)))
以下是detail.html中的表单
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'gamble:gambling' Profile.id %}" method="post">
{% csrf_token %}
{% for choice in coin.Face %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}"> {{ choice }}</label><br />
{% endfor %}
<input type="submit" value="flip" />
</form>
以下是models.py
中模型配置文件和硬币的代码# Create your models here.
class profile(models.Model):
name = models.CharField(max_length=120)
description = models.TextField(default='description default text')
def __unicode__(self):
return self.name
class Coin(models.Model):
#choice = models.ForeignKey(BetAmount, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200, default="...")
flip = randint(0,1)
Heads =0
Tails =1
Face ={
"Heads": Heads,
"Tails": Tails
}
def __str__(self):
return self.choice_text
def flipped(self):
return self.flip
我一直收到关于.get()的错误,即使我传递了表单名称,我也不确定它是否与Coin对象本身有关,此问题的清晰度会有所帮助。 在Coin模型中是否有我遗漏的东西,或者问题仍然在detail.html中,我似乎编写了尽可能接近教程示例的代码。