我用django的通用视图代码是这样的:
class IndexView(BaseView, ListView):
ismobile = True
if ismobile:
template_name = "m/index.html"
else:
template_name = 'index.html'
context_object_name = 'article_list'
paginate_by = settings.PAGE_NUM # 分页--每页的数目
def get_queryset(self):
article_list = Article.objects.filter(status=0)
return article_list
def get_context_data(self, **kwargs):
# 轮播
kwargs['home']= True
return super(IndexView, self).get_context_data(**kwargs)
大家可以帮我看下,我代码的第一句是ismobile = True意思就是判断是不是手机端方访问的.我的目的是想改成通过requests来判断,比如把代码改成这样
class IndexView(BaseView, ListView):
#手机访问,用手机模板
if 'm.maidu.com' in self.request.get_host():
template_name = "m/index.html"
电脑访问用电脑模板
else:
template_name = 'index.html'
.......
但是代码直接这样写会出错,会提示self不存在,我想下,如何优雅的解决这个问题?
3 回答
![?](http://img1.sycdn.imooc.com/545868b60001587202200220-100-100.jpg)
森林海
TA贡献2011条经验 获得超2个赞
试试这样的,不是用self,你类中应该写一个方法,这个方法其中有一个参数 是request
from django.utils.deprecation import MiddlewareMixin
class MultipleProxyMiddleware(MiddlewareMixin):
FORWARDED_FOR_FIELDS = [
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED_HOST',
'HTTP_X_FORWARDED_SERVER',
]
def process_request(self, request):
"""
Rewrites the proxy headers so that only the most
recent proxy is used.
"""
for field in self.FORWARDED_FOR_FIELDS:
if field in request.META:
if ',' in request.META[field]:
parts = request.META[field].split(',')
request.META[field] = parts[-1].strip()
![?](http://img1.sycdn.imooc.com/5458620000018a2602200220-100-100.jpg)
慕无忌1623718
TA贡献1744条经验 获得超4个赞
继承View类
在class IndexView(BaseView, ListView):添加View,即:
class IndexView(BaseView, ListView,View):就可以调用self.request
添加回答
举报
0/150
提交
取消