这是我的观点功能:
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是否具有适当的数据。我错过了什么?
答案 0 :(得分:1)
由于releaseContext
是字典,因此属性查找(x.y)不是您需要的,而是元素查找(x [y])。
所以而不是:
{{ releaseContext.release_id.buttonURL }}
使用
{{ releaseContext['release_id']['buttonURL'] }}
答案 1 :(得分:0)
在将值传递到模板之前,先尝试从字典中获取该值:
{% display = releaseContext['release_id']['buttonURL'] %}
{{ display }}