I have been reading around for other answers but i am still not understanding what is the quickest and best way to using common开发者_运维问答 code for multiple views.
Let's say i have this code, that reflects a user's points, that i want displayed in many of the views.
if(request.user.is_authenticated()):
# UserLove
userLove = 0
ul = Love.objects.filter(user=request.user.id)
for u in ul:
userLove += u.amount
else:
userLove= 0
I saw words about using decorators. I heard about generic views and subclassed views, and someone also mentioned context processors
Can you tell me which is best, and how would my code look if I had View1 and View2 as examples. Thanx!
Not sure I agree that either Decorators or Template Tags are the best approach here. Decorators are applied to the function (i.e. view), so for instance if you wanted to make sure that a user was logged in before they accessed a view, you could use a Decorator. But not for determining values inside the function.
If you have a block of code that you want to re-use in several places, just make it a separate function, maybe in a utilities file, then import the function. For instance:
# myapps.utilities.py
from models import Love
def computeLove(request):
# code for determining value here
return LoveValue
# someView.py
from myapps.utilities import computeLove
def showRatings(request):
lv = computeLove(request)
It's a standard programming method, you don't really need any specific Django features for this.
Okay, probably you need something else, but in your case you can do this thing using template tag, for example:
in appname/util.py you have to write the part of code which will return data you need. then in template tag you do something like
# appname_tags.py
from django import template
from appname.util import get_rating
register = template.Library()
@register.simple_tag
def user_rating(user):
rating = get_rating(user)
return rating if rating is not None else ''
so in your template file:
{% load appname_tags %}
{% user_rating anyuser %}
For this, writing either a Template Context Processor or a Template Tag is the best approach.
精彩评论