Login

Snippets by t_rybik

Snippet List

Parse custom template tag's args or kwargs

Enhanced version of snippet [1113](http://djangosnippets.org/snippets/1113/) Usage example (not self-contained): @register.tag def groupurl(parser, token): ''' Syntax:: {% groupurl view_name group [key=val, [key=val, ...]] [as varname] %} Example:: <a href="{% groupurl blog_detail group slug=blog.slug %}">{{ blog.name }}</a> ''' bits = token.contents.split() tag_name = bits[0] if len(bits) < 3: raise template.TemplateSyntaxError("'%s' takes tag at least 2 arguments (path to a view and a group)" % (tag_name,) bits_iter = iter(bits[1:]) # view_name + group and url kwargs args, kwargs = parse_args_and_kwargs(parser, bits_iter, stop_test='as', tagname=tag_name) if len(args) != 2: raise template.TemplateSyntaxError("'%s' takes exactly two non-kwargs (path to a view and a group)" % (tag_name,)) view_name, group = args # as var asvar = None for bit in bits_iter: asvar = bit return GroupURLNode(view_name, group, kwargs, asvar)

  • tag
  • templatetag
  • parse
  • args
  • kwargs
Read More

Get current user without a request object

Mechanism to obtain a `request.user` object without the `request` object itself. Requires `LocalUserMiddleware` in `MIDDLEWARE_CLASSES` settings variable. **Important**: works under assumption that within a web server each request is handled by a separate thread (as for example in the Apache HTTP server). **Beware**: [security threat](http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser), although ["thread locals only appears to be a security threat if a system has already been seriously compromised, at which point there'd be easier attacks to execute"](http://groups.google.com/group/django-users/browse_thread/thread/e7af359d7d183e04). **Dev note**: works fine with one-threaded Django's development server, each request resets current user; no worries 'bout many media requests - they won't (at least shouldn't) be using Django on the production server. **Ref**: originally found in the gatekeeper app.

  • middleware
  • user
  • request
  • local thread
Read More

Subdirectory and subcontext include template tag with examples

In principle it's a DRY code of a template node that can be used for creating project-wide template-tags. These can be used to display conceptually common blocks in templates with applications specific looks and content. E.g.: 1. application-specific info message, 2. model instances details in the list context, 3. login messages like 'Please login or signup to [some app-dependent text]' with appropriate url's, 4. standard forms (e.g with same CSS classes, displayed with uni_form). The code is profusely commented so look it up for details. Basically, when you have your project-wide `SubIncludeNode` tag defined, then just define appropriately named templates in applications template subdirectories e.g. `'profiles/_show_item.html'`. ** Example usage: login or signup message ** Let's say we are editing template rendered by the view indicated by the pattern named 'project_list' in the 'projects' app: {# those are equivalent #} {% login_or_signup %} {% login_or_signup project_list %} {% login_or_signup "project_list" %} {# academic purposes direct sub_include usage #} {# those two includes are also equivalent if there is no template called '_login_or_signup.html' in the 'projects' subdirectory #} {% url acct_signup as signup_url %} {% url acct_login as login_url %} {% url project_list as next_url %} {% sub_include "_login_or_signup.html" %} {% include "_login_or_signup.html" %} {# and those two are also equivalent if there is a template called '_login_or_signup.html' in the 'projects' subdirectory #} {% sub_include "_login_or_signup.html" from "projects" %} {% sub_include "_login_or_signup.html" %} {# also equivalent include if there is no variable called 'projects' in tempalte's context #} {% sub_include "_login_or_signup.html" from projects %} {# those are examples of using custom subcontext #} {% url acct_signup as signup_url %} {% url acct_login as login_url %} {% sub_include "_login_or_signup.html" from "default" with login_url,signup_url,next_url="/welcome" %} {% sub_include "_login_or_signup.html" with login_url="/login",next_url="/welcome",signup_url="/signup" %} ** Mored advanced usage proposal ** Say you have an subclasses of some model from the original app in a separate extending apps. You want to display subclasses instances differently using the original app templates. In the original app you do not know what the set of subclasses is (as the original app is not aware of the extending apps). Subclassing the `SubIncludeNode` you can override the `default_subdir` method such that it returns the app label of a model instance that was passed as a argument of your tag. This way you just put templates like `_show_instance.html` in extending apps subdirectories and voila - you have implementation of the overrideable templates displaying appropriately details about the model subclass instances.

  • templatetag
  • templatetags
  • include
Read More

Multiple querysets

This is an upgrade of snippet [1103](http://www.djangosnippets.org/snippets/1103/). Exemplary usage: class Blog(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Post(models.Model): title = models.CharField(max_length=50) blog = models.ForeignKey(Blog) def __unicode__(self): return self.title class Meta: abstract=True class Article(Post): text = models.TextField() class Link(Post): url = models.URLField() blog = Blog(name="Exemplary blog") blog.save() Article(title="#1", text="Exemplary article 1", blog=blog).save() Article(title="#2", text="Exemplary article 2", blog=blog).save() Link(title="#3", url="http://exemplary.link.com/", blog=blog).save() qs1 = Article.objects.all() qs2 = Link.objects.all() qsseq = QuerySetSequence(qs1, qs2) # those all work also on IableSequence len(qsseq) len(QuerySetSequence(qs2, qs2)) qsseq[len(qs1)].title # this is QuerySetSequence specific qsseq.order_by('blog.name','-title') excluded_homo = qsseq.exclude(title__contains="3") # homogenic results - returns QuerySet type(excluded_homo) excluded_hetero = qsseq.exclude(title="#2") # heterogenic results - returns QuerySetSequence type(excluded_hetero) excluded_hetero.exists() You can implement more `QuerySet` API methods if needed. If full API is implemented it makes sense to also subclass the `QuerySet` class.

  • queryset
  • chain
  • iterable
  • indexable
Read More

t_rybik has posted 5 snippets.