Django 1.3 - RequestContext not rendering to template - python

I am trying to simply render {{ request.user }} from my base template and for whatever reason it is not rendering anything. I have even tested trying to return {{ request }} to no avail.
I am currently using django-annoying to render to the template (render_to) and have tried to switch back to using django.templates.RequestContext and that hasn't worked either.
I have a feeling it has something to do with caching, but I have edited my template to show test - {{ request }} and "test - " shows up just fine.
I have also tried to upgrade my django to 1.4 alpha to see if it resolves my issue.
This does not send the request to the template
#render_to('profile/index.html')
def home(request):
return {}
This works
#render_to('profile/index.html')
def home(request):
return {'request': request}
However, if I pass 'request': request into the template everything works.
Link to settings.py
I can give any more information that is requested.

You need to add the django.core.context_processors.request context processor.

Related

Django - add context to request to be used by the view

Using Django I want to implement some middleware that will calculate some context that is to be used by the view itself.
For example, I have a middleware that looks at the request, and adds the user's permissions to the request, or some user configuration. The view looks at these permissions and decides how to handle the request using it.
This saves the need for multiple views (and multiple parts within the view) to query for this information.
I'm wondering what is the correct way to do that. One option is to just add request.user_permissions=... directly on the request. But is there some documented and expected way to do that?
There's no real documented way to do that, but Middleware is the correct place to do it and just adding properties to the request object is also the correct way.
You can confirm this, because Django is already doing it:
LocaleMiddelware
AuthenticationMiddleware
RemoteUserMiddleware
CurrentSiteMiddleware
SessionMiddleware
So just pick whatever is the most convenient data structure for your use case and tack that on to the request object.
This is not a perfect answer but at my experience I use this code. Every permission is saved in a boolean value which is true or false. You can access it in a html template like.
{% if request.user.is_admin %}
"Your code here"
{% else %}
"Your code here"
{% endif %}
and to send extra context you should create and pass an dicionary and pass it as as an argument to the render method from the view.
For eg:
def view(request, slug):
context = {'administrator':True}
blog_post = get_object_or_404(BlogPost, slug=slug)
context['blog_post'] = blog_post
return render(request, 'blog/detail_blog.html', context)
and access it like
{% if context.administrator %}
"Your code here"
{% else %}
"Your code here"
{% endif %}
I believe, since your middleware will calculate context, it should be implemented as context processor.
https://docs.djangoproject.com/en/3.1/ref/templates/api/#using-requestcontext
https://docs.djangoproject.com/en/3.1/ref/templates/api/#writing-your-own-context-processors

Trying to pass django-oscar products to custom template

I'm working on a custom template using a forked version of django-oscar apps (to have custom models).
I am trying to display a list of all the products in the product table, just to start with. I looked at django-oscar templates but as they rely on a lot of custom tempaltetags I found it too complex to rewrite everything to work with my models.
This is what I have in my views.py:
def product(request):
template = loader.get_template('/home/mysite/django_sites/my_site/main_page/templates/main_page/product.html')
prodlist = Product.objects.all()
return HttpResponse(template.render({}, request), context={'prodlist': prodlist})
And the code I am using in my template to try and display it
{% for instance in prodlist%}
<li>{{ instance.name }}</li>
{% endfor %}
However, this gives me an error
TypeError at /product/
__init__() got an unexpected keyword argument 'context'
/product corresponds to my product view in my urls.py
This was my best guess from following tutorials and looking at other answers. What am I getting wrong?
HttpResponse doesn't have context arg.
Seems like you need to add context into render.
Try:
context={'prodlist': prodlist}
return HttpResponse(template.render(context))

How to generate absolute urls in Django 2 templates

I have an html template, which is used to render an email, in that template, I want to attach verification links.
I am using the following code to generate the link
{% url 'verify_email' token=token email=email %}
but this one generates following URL instead of absolute URL.
I read this SO thread
How can I get the full/absolute URL (with domain) in Django?
and some initial google results but all of them seems old and not working for me.
TLDR: How do I generate absolute URLs in Django2 template files
You can use the build_absolute_uri() referenced in the other thread and register a custom template tag. Request is supplied in the context (that you enable via takes_context) as long as you have django.template.context_processors.request included in your templates context processors.
from django import template
from django.shortcuts import reverse
register = template.Library()
#register.simple_tag(takes_context=True)
def absolute_url(context, view_name, *args, **kwargs):
request = context['request']
return request.build_absolute_uri(reverse(view_name, args=args, kwargs=kwargs))
More on where and how to do that in the docs.
Then you can use the tag in your template like this:
{% absolute_url 'verify_email' token=token email=email %}

View all Object in Django Template

In this django function
def request(request):
args = {"name": "name", 'message': "message"}
return render(request, 'request.html', args)
the template will get {{name}} and {{message}} variable...
But apart from these two variable one can also access {{user}} and {{LANGUAGES}} object on template which are set in RequestContext by middleware.
Is there a way to displayed/render every object/variable that are sent to template either by my custom response or by any middleware like IP Address of requesting client, and other information.
You can get all variables and obj using debug
{% debug %}
If you want to print this vars for debugging only, try django debug toolbar
You can use the debug tag:
{% debug %}

How to pass information using an HTTP redirect (in Django)

I have a view that accepts a form submission and updates a model.
After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.
How can I "pass" this message to the other page? HttpResponseRedirect only accepts a URL. I've seen this done before on other sites. How is this accomplished?
This is a built-in feature of Django, called "messages"
See http://docs.djangoproject.com/en/dev/topics/auth/#messages
From the documentation:
A message is associated with a User.
There's no concept of expiration or
timestamps.
Messages are used by the Django admin
after successful actions. For example,
"The poll Foo was created
successfully." is a message.
You can use django-flashcookie app
http://bitbucket.org/offline/django-flashcookie/wiki/Home
it can send multiple messages and have unlimited types of messages. Lets say you want one message type for warning and one for error messages, you can write
def simple_action(request):
...
request.flash['notice'] = 'Hello World'
return HttpResponseRedirect("/")
or
def simple_action(request):
...
request.flash['error'] = 'something wrong'
return HttpResponseRedirect("/")
or
def simple_action(request):
...
request.flash['notice'] = 'Hello World'
request.flash['error'] = 'something wrong'
return HttpResponseRedirect("/")
or even
def simple_action(request):
...
request.flash['notice'] = 'Hello World'
request.flash['notice'] = 'Hello World 2'
request.flash['error'] = 'something wrong'
request.flash['error'] = 'something wrong 2'
return HttpResponseRedirect("/")
and then in you template show it with
{% for message in flash.notice %}
{{ message }}
{% endfor }}
or
{% for message in flash.notice %}
{{ message }}
{% endfor }}
{% for message in flash.error %}
{{ message }}
{% endfor }}
I liked the idea of using the message framework, but the example in the django documentation doesn't work for me in the context of the question above.
What really annoys me, is the line in the django docs:
If you're using the context processor, your template should be rendered with a RequestContext. Otherwise, ensure messages is available to the template context.
which is incomprehensible to a newbie (like me) and needs to expanded upon, preferably with what those 2 options look like.
I was only able to find solutions that required rendering with RequestContext... which doesn't answer the question above.
I believe I've created a solution for the 2nd option below:
Hopefully this will help someone else.
== urls.py ==
from django.conf.urls.defaults import *
from views import *
urlpatterns = patterns('',
(r'^$', main_page, { 'template_name': 'main_page.html', }, 'main_page'),
(r'^test/$', test ),
== viewtest.py ==
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
def test(request):
messages.success( request, 'Test successful' )
return HttpResponseRedirect( reverse('main_page') )
== viewmain.py ==
from django.contrib.messages import get_messages
from django.shortcuts import render_to_response
def main_page(request, template_name ):
# create dictionary of items to be passed to the template
c = { messages': get_messages( request ) }
# render page
return render_to_response( template_name, c, )
== main_page.html ==
{% block content %}
{% if messages %}
<div>
{% for message in messages %}
<h2 class="{{message.tag}}">{{ message.message }}</h2>
{% endfor %}
</div>
{% endif %}
{% endblock %}
I have read and checked all answers, and it seems to me that the way to go now is using the messaging framework. Some of the replies are fairly old and have probably been the right way at the time of the posting.
There is a lot of solutions
1 Use Django-trunk version - it support sending messages to Anonymous Users
2 Sessions
def view1(request):
request.session['message'] = 'Hello view2!'
return HttpResponseRedirect('/view2/')
def view2(request):
return HttpResponse(request.session['message'])
3 redirect with param
return HttpResponseRedirect('/view2/?message=Hello+view2')
4 Cookies
Can you just pass the message as a query param oon the URL to which you're redirecting? It's not terribly RESTy, but it ought to work:
return HttpResponseRedirect('/polls/%s/results/?message=Updated" % p.id)
and have that view check for a message param, scrub it for nasties, and display it at the top.
I think this code should work for you
request.user.message_set.create(message="This is some message")
return http.HttpResponseRedirect('/url')
Take a look at Django's messages framework. http://docs.djangoproject.com/en/dev/ref/contrib/messages/#ref-contrib-messages
You could also have the redirect url be the path to an already parameterized view.
urls.py:
(r'^some/path/(?P<field_name>\w+)/$', direct_to_template,
{'template': 'field_updated_message.html',
},
'url-name'
),
views.py:
HttpResponseRedirect( reverse('url-name', args=(myfieldname,)) )
Note that args= needs to take a tuple.
The solution used by Pydev UA is the less intrusive and can be used without modifying almost nothing in your code. When you pass the message, you can update your context in the view that handles the message and in your template you can show it.
I used the same approach, but instead passing a simple text, passed a dict with the information in useful fields for me. Then in the view, updated context as well and then returned the rendered template with the updated context.
Simple, effective and very unobstrusive.
While all suggestions so far work, I would suggest going with Ry4an's (pass it in the request URL) - just change the actual text to a coded text within a predefined set of text messages.
Two advantages here:
Less chance of something hacking through your scrubbing of bad content
You can localize your messages later if needed.
The other cookie related methods.. well, they don't work if the browser doesn't support cookies, and are slightly more expensive.. But only slightly. They're indeed cleaner to the eye.

Categories

Resources