Guys, I can not enter, why the function does not work. HTML string:

<a href="/articles/addlike/{{ article.id }}/"><img src="{% static "like.jpg" %}" width="25px" height="25px"></a>{{ article.article_likes }} 

URL pattern:

 urlpatterns = [ url(r'^1/', views.basic_one), url(r'^articles/all/$', views.articles), url(r'^articles/get/(?P<article_id>\d+)/$', views.article), url(r'^', views.articles), url(r'^articles/addlike/(?P<article_id>\d+)/$', views.addlike, name='addlike'), url(r'^articles/addcomment/(?P<article_id>\d+)/$', views.addcomment), ] 

View:

 def addlike(request, article_id): try: article = Article.objects.get(id=article_id) article.article_likes += 1 #в модели поле models.IntegerField(default=0) article.save() except ObjectDoesNotExist: raise Http404 return redirect('/') 

It does not generate errors, after clicking on the icon on the browser, which should increase the value in the database by 1, everything remains in the same place, the value in the database does not change, the link in the address bar will look like http://127.0.0.1:8000/ articles / addlike / 1 / and everything ... Where to drip?

    1 answer 1

    Show the entire urls.py, most likely the URL in the dispatcher is intercepted for you due to the lack of $ at the end of the line and does not get into the desired twist.

    I can generally simplify the view

     from django.shortcuts import get_object_or_404 def addlike(request, article_id): article = get_object_or_404(Article, article_id) article.article_likes += 1 article.save() return redirect('/') 

    In the dispatcher, you can call the url, so that in html you can avoid the hardcode in the links

     url(r'^articles/addlike/(?P<article_id>\d+)/$', views.addlike, name="add_like") 

    In the template:

     <a href="{% url add_like article_id %}"> 
    • All urls list: urlpatterns = [url (r '^ 1 /', views.basic_one), url (r '^ articles / all / $', views.articles), url (r '^ articles / get / (? P <article_id> \ d +) / $ ', views.article), url (r' ^ ', views.articles), url (r' ^ articles / addlike / (? P <article_id> \ d +) / $ ', views .addlike, name = 'addlike'), url (r '^ articles / addcomment / (? P <article_id> \ d +) / $', views.addcomment),] - moffire
    • I hs how to format the code normally in the comments ... Sori - moffire
    • try changing url (r '^', views.articles), to url (r '^ $', views.articles), - flawless
    • Earned !! Buddy, thank you so much)) - moffire