0
這是我的看法功能:無法存取Django模板內的字典值
def detail(request, movie_id):
movie = Movie.objects.get(id = movie_id)
movieReleases = Release.objects.filter(movie = movie)
reviews = Review.objects.filter(movie = movie)
initRating = 0
if request.user.is_authenticated():
user = Account.objects.get(user = request.user.id)
try:
myreview = Review.objects.get(movie = movie, user = user)
initRating = myreview.rating
except:
pass
releaseContext = dict()
for release in movieReleases:
if release.isReleased():
releaseContext[release.id] = {'buttonURL' : reverse('movies.views.add', args=(release.id,)), 'buttonText' : 'Add to cart'}
elif MovieReleaseReminder.objects.filter(account=user, movie=release).exists():
releaseContext[release.id] = {'buttonURL' : reverse('movies.views.unsubscribeFromReleaseReminder', args=(release.id,)), 'buttonText' : 'Unsubscribe from release reminder'}
else:
releaseContext[release.id] = {'buttonURL' : reverse('movies.views.subscribeForReleaseReminder', args=(release.id,)), 'buttonText' : 'Subscribe to release reminder'}
if MovieUpdateSubscription.objects.filter(account=user, movie=movie).exists():
movieSubscribeURL = reverse('movies.views.unsubscribeFromUpdates', args=(movie.id,))
movieSubscribeButtonText = 'Unsubscribe from updates'
else:
movieSubscribeURL = reverse('movies.views.subscribeForUpdates', args=(movie.id,))
movieSubscribeButtonText = 'Subscribe for updates'
else:
releaseContext = None
movieSubscribeURL = None
movieSubscribeButtonText = None
averageRating = calculateAverageRating(movie)
t = loader.get_template('movies/detail.html')
c = RequestContext(request, {'movie' : movie,
'movieReleases' : movieReleases,
'releaseContext' : releaseContext,
'reviews': reviews,
'averageRating': averageRating,
'initRating': initRating,
'movieSubscribeURL' : movieSubscribeURL,
'movieSubscribeButtonText' : movieSubscribeButtonText})
return HttpResponse(t.render(c))
這裏是有問題的模板代碼:
{% if movieReleases%}
<table border="1px">
{% for release in movieReleases %}
<tr>
<td>{{release.format}}</td>
<td>{{release.region}}</td>
<td>{{release.price}}</td>
{% if user.is_authenticated %}
{% with release_id=release.id %}
<td><form action="{{ releaseContext.release_id.buttonURL }}" method="post">{% csrf_token %}<input type="submit" value="{{ releaseContext.release_id.buttonText }}" /></form></td>
{% endwith %}
{% endif %}
</tr>
{% endfor %}
</table>
{% endif %}
的問題是,無論{{ releaseContext.release_id.buttonURL }}
和{{ releaseContext.release_id.buttonText }}
正在評估向空字符串,即使我已經在調試器中檢查了releaseContext具有適當的數據。我錯過了什麼?
哦,我不知道,你可以在模板中使用的方括號。我記得在某處使用'。'使得Django以某種順序嘗試所有的成員,方法,字典查找,所以我認爲它是唯一的操作符。 – Bwmat 2012-08-02 03:26:07
annnnnnnnnd it does not work.TemplateSyntaxError at/movies/detail/4/ 無法解析其餘部分:'[release.id] ['buttonURL']'from'releaseContext [release.id] ['buttonURL'] ' – Bwmat 2012-08-02 03:39:24
從你粘貼的東西看,它在引用中似乎仍然是錯誤的。它應該是'releaseContext ['release_id'] ['buttonURL']' – 2012-08-04 02:48:49