A
A
Artur Zenkov2015-08-01 19:38:11
Django
Artur Zenkov, 2015-08-01 19:38:11

How to implement an if/else condition in Django CBV?

I feel that this code is implemented incorrectly (code duplication), but I don’t know how to make an if / else condition in the class.
That is, I want a parameter to be passed to the url and on its basis a decision was made in the condition.
urls.py

urlpatterns = [
    url(r'^(?P<pk>\d+)/$', ArticleDetail.as_view()),
    url(r'^add_like/(?P<pk>\d+)/$', ArticleDetail_add_like.as_view()),
]

views.py
class ArticleDetail(DetailView):
    model = Article
    template_name = "articles/article.html"

class ArticleDetail_add_like(DetailView):
    model = Article
    template_name = "articles/article.html"

    def get_object(self):
        object = super(ArticleDetail_add_like, self).get_object()
        object.article_likes += 1
        object.save()
        return object

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pinkevich, 2015-08-01
@Hrom

not quite understood, but if you want to remove code duplication, you can inherit from ArticleDetail:

class ArticleDetailView(DetailView):
    model = Article
    template_name = "articles/article.html"

class ArticleDetailAddLikeView(ArticleDetailView):

    def get_object(self):
        object = super(ArticleDetailAddLikeView, self).get_object()
        object.article_likes += 1
        object.save()
        return object

M
marazmiki, 2015-08-02
@marazmiki

Inheritance, of course, will allow you to get rid of code duplication, but there are two points: firstly, you change the functionality of get_object () and make it write something, which in itself is ugly from the programmer's point of view :) if you go this way initially wrong way (I will explain why wrong way below), then I think it would be more beautiful to override dispatch().
Secondly, and most importantly, it is not recommended for anyone to do saving operations on the GET, HEAD and OPTIONS HTTP methods. At least for those reasons that a few seconds after you first request them, all sorts of Googlebots will fly in and wind up the counters. And it's good if a denial of service is not called.
It is considered good form and common sense to use the POST method for persisting views. Or, even better, use a RESTful approach with POST, PUT, and DELETE to create, modify, and delete, respectively.
Specifically, in your case, it seems to me that it is best to use a FormView for the counter increment view. Or UpdateView, the get_object() method is already implemented there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question