我有一个用户可以收藏并保存到自己帐户的帖子列表。但是,我一直收到上面的错误消息。有没有人知道问题出在哪里?
views.py:
def AircraftFavourite(request, id=None):
instance = get_object_or_404(Aircraft, id=id)
queryset = Aircraft.objects.all()
context = {'all_aircraft' : queryset}
try:
selected_aircraft = context.all_aircraft.get(pk=request.POST['context'])
except(KeyError, Aircraft.DoesNotExist):
return render(request,'aircraft.html', {
"aircraft" : instance,
"error_message" : "You did not select a valid aircraft",
})
else:
selected_aircraft.is_favorite = True
selected_aircraft.save()
return render(request,'aircraft.html', context)
urls.py
urlpatterns = [
url(r'^detail/(?P<id>\d+)/$', AircraftDetail, name='AircraftDetail'),
url(r'^(?P<id>\d+)/favourite/$', AircraftFavourite, name='AircraftFavourite'),]
aircraft.html
{% block content %}
{% for a in all_aircraft %}
<table>
<tr>
<th><a href="{% url 'AircraftDetail' id=a.id %}"> {{ a.title }}</a>
</th>
</tr>
<tr>
<td>
<form action="{% url 'AircraftFavourite' id=a.id %}" method="post">
{% csrf_token %}
<input type="submit" id="aircraft{{ forloop.counter }}" name ="aircraft" value="{{ a.id }}">
<label for="aircraft{{ forloop.counter }}"
{% if aircraft.is_favourite %}
<img src="http://i.imgur.com/b9b13Rd.png" />
{% endif %}
<input type="submit" value="Favourite"><br>
</form>
</td>
</tr>
</table>
{% endfor %}
{% endblock %}
答案 0 :(得分:0)
在django模板中,属性访问和项目访问是等效的:
#rendered with context = dict(a=dict(something=5), b=SomeObject))
<body>
{{ a.something }} vs {{ b.something }}
</body>
两者都有效,django会确定是否要访问该属性或获取该项目。
但是在Python中,使用.
的属性访问不等同于使用方括号[ ]
的项目访问权限。
您的脚本应该更改以反映这一点:
try:
selected_aircraft = context['all_aircraft'].get(pk=request.POST['context'])
或者理想情况下直接访问查询集,因此代码更能反映您正在做的事情:
try:
selected_aircraft = queryset.get(pk=request.POST['context'])
答案 1 :(得分:0)
更改为:
selected_aircraft = get_object_or_404(Aircraft, id=request.POST['context'])