我正在尝试使用Django制作一个简单的火箭预订系统。但是,每次我尝试预订机票时,都会收到Forbidden 403错误:CSRF token missing or incorrect
。
这是我的代码:
class Tickets(models.Model):
rocket_line = models.ForeignKey('Rockets')
date = models.DateField()
number_of_seats = models.IntegerField()
email = models.CharField(max_length=50)
ordered_on = models.DateTimeField()
total_price = models.DecimalField(max_digits=10, decimal_places=2)
def __unicode__(self):
return str(self.id)
def order(request):
if request.method == 'POST':
order = Tickets(
rocket_line = Rockets.objects.get(id=request.POST['rocket_line']),
date=request.POST['date'],
number_of_seats=request.POST['number_of_seats'],
email=request.POST['email'],
ordered_on=datetime.now(),
total_price=(float(number_of_seats) * float(Rockets.objects.get(id=request.POST['rocket_line']).rprice))
)
order.save()
return HttpResponseRedirect('/menu/')
else:
all_rockets = Rockets.objects.all().order_by('rtime')
return render_to_response('order.html', { 'all_rockets': all_rockets}, RequestContext(request))
<h1>You can order a ticket here:</h1>
<form action="/order/" method="post">
<p>
<label>Rocket_line</label>
<select name="rocket_line">
{% for rocket in all_rockets %}
<option value="{{ rocket.id }}">{{ rocket }}</option>
{% endfor %}
</select>
<label>Date</label>
<input name="date" value="YYYY-MM-DD" type="text" size="10" />
<label>Number of seats</label>
<input name="number_of_seats" value="" type="text" size="10" />
<label>E-mail</label>
<input name="email" value="@" type="text" size="50" />
<br /><br />
<input class="button" value="Order" type="submit" />
</p>
</form>
<br />
你能帮我解决一下问题所在吗?
答案 0 :(得分:6)
取自全能的django的docs:
第1步:
将中间件'django.middleware.csrf.CsrfViewMiddleware'添加到您的中间件类列表MIDDLEWARE_CLASSES中。 (它应该出现在假设已经处理了CSRF攻击的任何视图中间件之前。)
第2步:
<form action="." method="post">{% csrf_token %}
您需要将{%csrf_token%}添加到模板中。
还有其他解决方案(装饰器或基于ajax),但这个是最快和最常用的(我认为,至少......它无需任何麻烦实施)