我是django的新手。我现在正在编码一个urlshortner,我想广告功能以读取Http引用,以计算从各种社交平台上单击链接的次数。
文档中指出django.http中包含的HttpRequest对象将使用-HttpRequest.META ['HTTP_REFERER']
提取该对象所以我这样做是为了打印出其中包含的信息的类型-
from django.http import HttpRequest
from .models import UrlSave
def display(request,id):
print(HttpRequest.META['HTTP_REFERER'])
try:
short_url = UrlSave.objects.get(pk=id)
visit_time = short_url.times_visited
short_url.times_visited = short_url.times_visited+1
url = short_url.to_view
short_url.save()
context = {'visit':visit_time,'url':url}
return render(request,'shorturl/previsit.html',context)
except:
return HttpResponse('Wrong Url')
但是当我访问链接时,它会在CLI中打印出错误- AttributeError:类型对象'HttpRequest'没有属性'META'
即使经过许多stackoverflow页面,我也无法找出原因 请帮助
答案 0 :(得分:3)
您无法像类属性一样通过访问获得请求的META
,特定的请求是request
参数,因此可以使用request.META['HTTP_REFERER']
进行访问:>
from django.http import HttpRequest
from .models import UrlSave
def display(request, id):
print(request.META['HTTP_REFERER'])
try:
short_url = UrlSave.objects.get(pk=id)
visit_time = short_url.times_visited
short_url.times_visited = short_url.times_visited+1
url = short_url.to_view
short_url.save()
context = {'visit':visit_time,'url':url}
return render(request,'shorturl/previsit.html',context)
except:
return HttpResponse('Wrong Url')