H
H
happiva2019-06-23 17:32:40
Django
happiva, 2019-06-23 17:32:40

How to call a function in a template?

I understand that the question is simple, but still there is a misunderstanding

class CollDetailView(DetailView):
    model = Art
    template_name = 'art_detail.html'
    queryset = Art.objects.all_with_related_persons_and_score()

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data()
        if self.request.user.is_authenticated:
            voted = Like.objects.get_vote_or_unsaved_blank_vote(
                author_by=self.request.user,
                art_ident=self.get_object()
            )
            if not voted and self.request.user.access_to_golos:
                obj = self.get_object()
                add_like(obj=obj, user=self.request.user)
       
        else:
            pass
        return ctx

The function itself
def add_like(user, obj):
    obj_type = ContentType.objects.get_for_model(obj)
    like = Like.objects.get_or_create(
        content_type=obj_type, art_ident=obj.slug, author_by=user)
    return reverse('art_detail')

Maybe you can somehow shove the function call in ctx
?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Chichak, 2019-06-28
@ilya_chch

if this is a system of likes, then I would suggest writing a simple API endpoint, and send a JavaScript POST request there, in which to pass the id. if there is no like and it was successfully created, the API returns status 201 and something like {'like': 'OK'} and the button somehow changes. If the like was given, the like is removed and a 204 status and a response like {'like': 'REMOVED'} is returned.
Well, about the question - initially, template tags are most suitable for executing a function in a template. But they are executed during page rendering.
if the API is not your option, you can make a RedirectView, and a button that should perform this function, hang a link to this view. in the get_redirect_url method you write your own logic and return the same url that came from via request.META.

S
szelga, 2019-06-28
@szelga

you can file your template tag, for example. but I join the previous speakers, it's ugly, it's better to separate the logic from the presentation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question