Question

I am retrieving a bunch of things with a queryset and displaying them as a list, that is then clickable to view the chosen article's details. So in the article's details view, I have a is_creator method:

@login_required
def is_creator(userProfile, article):
    if userProfile == article.creator:
        return True
    else:
        return False

So I can display an edit button at will. On the homepage though, it's a different story because I'm making a query, and giving the queryset directly to the template that will make a for loop to display the titles. I still want to know for each article if the current user is the creator though.

So I'm thinking of adding the work in the model itself, not to have to duplicate code anywhere.

@property
def is_creator(self,user):
    if self.creator.user == user:
        return 1
    else:
        return 0

I was thinking that by adding that in the model, I should be able to call in the template {% if event.is_creator user %}test{% endif %} pretty easily. Seems that I'm wrong, because I'm facing:

TemplateSyntaxError at /
Unused 'user' at end of if expression.

I'm coming from the PHP world so it feels like this should work, but I'm obviously doing something wrong.

Thanks in advance :)

EDIT: I'm guessing that another solution would be in the view to loop through the Queryset with something like:

 variables['articles'] = Event.objects.filter(
            (Q(creator=me) | Q(bringing__attendee=me)) & Q(date_start__lt=datenow) & Q(date_end__gt=datenow)
        ).order_by('-date_start')
    for article in variables['articles']:
         article.iscreator=1 (I can do some more work here)

But it seems like having to loop over the QS is not the best idea.

Was it helpful?

Solution

It is very sad but you cant pass params to methods from templates(indeed this is a good idea - so you don't mix presentation logic with model logic, almost :) ). You have to write a template tag for this purpose.

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

tag would look like this(not tested):

@register.simple_tag(takes_context=True) #  assuming you are running in request context
def current_user_is_creator(context,article):
    user = context['request'].user
    return article.creator.user == user  #  dont forget to add proper checks

Or you could prepare required data in the view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top