Code

Changes between Version 9 and Version 10 of TemplatePitfalls


Ignore:
Timestamp:
09/16/05 10:38:37 (9 years ago)
Author:
L.Plant.98@…
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • TemplatePitfalls

    v9 v10  
    3737I'm posting this to atone for my previous crummy advice on this Wiki page. {{{- garthk}}} 
    3838 
    39 ''But what if your custom template tags needs access to the HttpRequest object in order to do it's stuff?  For example, if you have a menu or a breadcrumb that depends on {{{request.path}}}, or on the session etc?  Does the DjangoContext object provide access to this in any way?  The only ways I've found are things like subclassing DjangoContext and getting that to use the request to create any data needed for the base templates/custom template tags, but that won't work with generic views AFAIK.  (I'm happy using my current method, as I haven't actually used generic views yet, but imagine I may need to soon). Cheers.'' 
     39The problem with the above is that 'the function of your choice' might need to take the HttpRequest object as an argument, which isn't currently possible.  An alternative solution is to call the generic views manually, rather than automatically via the URL dispatcher.  With this method, you set URL dispatcher to call your custom view function, which simply sets gets any required extra context variables, using the request object, then calls the relevant generic view function.  For example: 
    4040 
    41 I had a chat to Adrian about that. They haven't yet seen a compelling reason to have {{{DjangoContext}}} stash a copy of {{{request}}}, and indeed it turned out that there was an easy workaround to my use case (access to the request path for my login system). If you have a good use case, submit a ticket. {{{ - garthk }}} 
     41{{{ 
     42#!python 
     43from django.views.generic import list_detail 
    4244 
    43 ''What was your workaround? I think I'm going to need the same thing, as I'll need access to cookies/session for some other login-related common content, which won't use Django's own 'user' functionality.  Cheers - luke'' 
     45def index(request): 
     46 return list_detail.object_list(request, 'your_app_name', 'model_module_name',  
     47  extra_context = do_something_with_request(request), 
     48  template_name = 'your_template_name', 
     49  paginate_by=50) 
     50}}} 
     51 
     52This also has the advantage that every argument to object_list() can be dynamic and depend on the request, e.g. paginate_by could be a user preference or a query string parameter.  I'm not sure if this is a perfect solution, but it's pretty easy. {{{ - luke plant }}}