python more and more fire, a lot of friends in the web direction, Django framework is a framework in most of today small ape circle for everyone Detailed look at Django browser page hits, friends who are interested can learn, no matter what website, this knowledge It is certainly used.
Typically written directly in a view Views.py function can, because each time point by view illustrating details will function processing,
So can "+1" operation on the views in this view function.
Corresponding url: url (r '? ^ (P <pk> [0-9] +) / $', views.get_detail, name = 'detail'),
def get_detail(request, pk=''):
# 根据文章的id 对每一次点击累加
context = Text.objects.get(id=pk)
browses = context.browse
browses += 1
context.browse = browses
context.save()
return render(request, 'news/detail.html',{'context':context})
复制代码
But this official document to go along with Django, use: generic.DetailView subclasses:
Then we know that it has these methods:
1.dispatch()
2.http_method_not_allowed()
3.get_template_names()
4.get_slug_field()
5.get_queryset()
6.get_object()
7.get_context_object_name()
8.get_context_data()
9.get()
10.render_to_response()
复制代码
Finally, the next test get, I wrote the following:
对应的url:url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
class DetailView(generic.DetailView):
model = Text
template_name = 'news/detail.html'
context_object_name = 'blog'
def get_queryset(self):
return Text.objects.filter(pub_date__lte=timezone.now())
def get(self, request, *args, **kwargs):
# 根据文章的id 对每一次点击累加
blog = Text.objects.get(id=kwargs['pk'])
browses = blog.browse
browses += 1
blog.browse = browses
blog.save()
return render(request, 'news/detail.html', {'blog': blog})
复制代码
In fact, the key to get specific objects, so this place needs "id", it needs to be captured from the url "pk",
** kwargs but this value may be by kwargs [ 'pk'] to obtain it.
To end here, you learn Django hits browse the page yet? Feeling of doubt, multi-read it over twice, I believe we'll get it; interested, you can go to a small circle ape learn more things, learn that a little progress every day.
Reproduced in: https: //juejin.im/post/5d0b2e176fb9a07f065573c0