tags:

views:

27

answers:

1

I wrote a wrapper around render_to_response that looks like this

from app import constants

def response(request, template, vars={}):
    if '.' not in template:
        template += '.html'
    template_vars = {}

    for constant in dir(constants):
        if constant[:2] == '__': continue
        template_vars[constant] = getattr(constants, constant) # BUG: causes you to stay logged in
    template_vars.update({'settings':settings})
    template_vars.update({'request':request})
    template_vars.update(vars)

    return render_to_response(template, template_vars, context_instance=RequestContext(request))

It seems that by adding the constants to the template vars, user.is_authenticated always returns true in the template, and user.username gets its value from some random user (most recently registered or something). Just wondering why that is?

Anyone care to explain?

If I print the constants, these are them

BidReasons
BidStatuses
CA_PROVINCES
COUNTRIES
CancellationRequestStatuses
EMAIL_NOTIFICATIONS
Enum
Flags
InvoiceStatuses
NA_REGIONS
PaymentMethods
PaymentTimes
PaymentTypes
SELECT_OPTION
SecretKeyPurposes
Sequence
ServiceTypes
ShipmentStatuses
USER_RATINGS
US_STATES
VehicleListingOptions
WeekDays
YES_OR_NO

I don't see anything in there that would mess with user


My new fix, if curious:

def response(request, template, vars={}):
    if '.' not in template:
        template += '.html'

    template_vars = {'settings':settings, 'request':request, 'constants':constants.__dict__}
    template_vars.update(vars)

    return render_to_response(template, template_vars, context_instance=RequestContext(request))
+1  A: 

Not really related to your question, but if you want to add variables to your template context, rather than calling a separate function in each view you might want to look into context processors which do the same thing automatically.

Daniel Roseman
Hrm... didn't think about that. Good suggestion! I still wanted to get rid of that nasty `context_instance=RequestContext(request)` bit though. It used to use a default template based on the view func name too...but that didn't pan out.
Mark