Sunday, July 29, 2012

Re: Is there a way to use 'request.user' in a custom template tag without an inclusion tag?

Well holy crap!! context['user'] worked perfectly! I thought I would have to come up with some crazy workaround!
Thank you kindly sir.


On Sunday, 29 July 2012 15:03:13 UTC-4, Ash Courchene wrote:
So I made a custom template tag that allows pieces of content to be edited by the site administrator with the click of a link.
For instance, if i put {% editable 'index_block_one' %}, it would return whatever content is in the Placeholder model I created with the name "index_block_one".
The code below, for the template tag:

from django import template
from django.contrib.auth.models import User
from cms.models import Placeholder

register = template.Library()

@register.tag(name="editable")
def do_editable(parser, token):
try:
tag_name, location_name = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires a single argument." % token.contents.split()[0])
if not(location_name[0] == location_name[-1] and location_name[0] in ('"', "'")):
raise template.TemplateSyntaxError("%r tag's arguments should be in quotes." % tag_name)
return EditableNode(location_name, context)

class EditableNode(template.Node):
def __init__(self, location_name):
self.location_name = location_name.encode('utf-8').strip("'")
def render(self, context):
obj = Placeholder.objects.filter(location=self.location_name)
if request.user.is_authenticated():
for x in obj:
return "%s<br/><a href='/admin-edit/%s'>edit</a>" % (x, self.location_name)
else:
for x in obj:
return x

I want this to return a link that says "Edit" if the site administrator is logged in, and just the content if the administrator is not logged in. However, I get an error saying "global name 'request' is not defined". I did put django.core.context_processors.request and .auth in my settings file. And still nothing.

So I did some research that said that an inclusion tag is the way to go, except I don't have an html file as a template, because this template tag is returning a Model object(??). There's no html to show..... SO. Is there a way to use request.user in this template tag without the use of an inclusion tag? If someone could point me in the right direction, that'd be great.... And hopefully all this made sense. Thanks again.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/JI7BDqMOMw0J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment