Hello I'm newbie in Django,
I'm looking to creating custom error pages to my app and found this site: http://blog.eliacontini.info/post/118617321553/django-custom-error-pages
However the 'render_to_response' is not used in Django 1.10
How do I transcript this code to Django 1.10
With best regards.
render_to_response() still works in Django 1.10, but if you want to use the more classical approach, you can use render(). Example:
from django.shortcuts import render
def myview(request):
if request.METHOD == 'GET':
context = {}
return render(request, 'index.html', context, status=404)
Django 1.10 passes three parameters to the page_not_found (https://docs.djangoproject.com/en/1.10/ref/views/#django.views.defaults.page_not_found)
create a function in your custom exceptions view
from django.shortcuts import render
def page_not_found(request, exception, template_name='404.html'):
return render(request, "page-not-found.html", context=None, status=404)
then add this line to your urls.py
handler404 = 'path_to_exceptions_view.page_not_found'
Related
For example i have a admin app in a django project. I have 2 view function in views.py like as
views.py
from django.shortcuts import render, redirect
from .models import Manager
def admin_home(request):
manager = 'manager'
context ={
'manager':manager,
}
return render(request, 'home/index.html', context)
def admin_show(request):
manager = Manager.objects.all()
context ={
'manager':manager,
}
return render(request, 'home/index.html', context)
But i want to write both function in a class. like as
from django.shortcuts import render, redirect
from .models import Manager
from django.views import View
class AdminPart(View):
def admin_home(request):
manager = 'manager'
context ={
'manager':manager,
}
return render(request, 'home/index.html', context)
def admin_show(request):
manager = Manager.objects.all()
context ={
'manager':manager,
}
return render(request, 'home/index.html', context)
Isn't it possible in django like as python class. please help me....
There are class based views in Django.
Here read the docs:
https://docs.djangoproject.com/en/3.1/topics/class-based-views/
or maybe try this tut:
https://www.youtube.com/watch?v=-tqhhT3R6VY
Hope this helps! (:
You can also use Django rest framework, it provides many feature-rich types of class-based views like generic api view, viewset
https://www.django-rest-framework.org/tutorial/3-class-based-views/
I am using Django 1.11 and django-settings-export, but it is not working for this view:
from django.shortcuts import render_to_response
def foo(request):
return render_to_response('foo.html', {})
Fixed changing render_to_response to render.
from django.shortcuts import render
def foo(request):
return render(request, 'foo.html', {})
Checking Django documentation, render_to_response is not recommended and will be deprecated.
This function preceded the introduction of render() and works similarly except that it doesn’t make the request available in the response. It’s not recommended and is likely to be deprecated in the future.
I'm new to django. Problem: to see my homepage (that shows the default django login form)
i have to write the addess:
x.x.x.xxx:8001/login
I would like to access it directly through that:
x.x.x.xxx:8001
What i can see now if i digit x.x.x.xxx:8001, is the login page without the form.
I have:
in my urls.py:
urlpatterns = patterns('',
url(r'^$', 'license.views.index', name='auth_login'),
in my views.py
from django import template
from django.shortcuts import render_to_response
from django.views.decorators.vary import vary_on_cookie
#vary_on_cookie
def index(request):
return render_to_response('login.html', {
}, context_instance = template.RequestContext(request))
That is because you are not passing a login form instance to your form.
Unless you want to perform some custom stuff in your view, your best bet is to use Django's built-in login view. You can set a custom template for it:
url(r'^$', 'django.contrib.auth.views.login', {'template_name': 'login.html'})
See this page for more info: django.contrib.auth.views.login (v1.5) docs
Now, I see that you are using a decorator on your view, which implies that you do indeed want to perform custom stuff. In that case, I believe you'll want to use the django.contrib.auth.forms.AuthenticationForm. Try doing something like this in your view:
from django.contrib.auth.forms import AuthenticationForm
from django.shortcuts import render
from django.views.decorators.vary import vary_on_cookie
#vary_on_cookie
def index(request):
form = AuthenticationForm(data=request.POST or None)
return render(request, 'login.html', {
'form': form
})
This is my views.py:
# Create your views here.
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.db import models
from display.forms import CodeForm
from display.forms import CodeFormSet
from ExamPy.questions.models import QuestionBase
def codepost(request):
if request.method == 'POST':
form = CodeFormSet(request.POST)
if form.is_valid():
titles = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
title = form.cleaned_data['title']
if title in titles:
raise forms.ValidationError("Articles in a set must have distinct titles.")
titles.append(title)
return render_to_response('quesdisplay.html')
else:
form = CodeFormSet()
return render_to_response('quesdisplay.html', {'form':form})
Thus, when I click on submit button, it should show the quesdisplay.html without any form in it. But, it is taking me to some contact page which doesn't even exist.
Error:
The current URL, contact/, didn't match any of these.
I've tried all possible ways to debug this but its not possible as there is no trace of anything called "contact" in this.
Edit:
This is the warning I get:
/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py:101: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.
warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.")
[10/Nov/2011 05:34:17] "
As seen in the comment before, using Requestcontext solve your problem.
Here is the documentation about csrf_token : https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#how-to-use-it
As we can read :
Use RequestContext, which always uses
'django.core.context_processors.csrf' (no matter what your
TEMPLATE_CONTEXT_PROCESSORS setting). If you are using generic views
or contrib apps, you are covered already, since these apps use
RequestContext throughout.
So here it seems we're not using a generic view, neither a contrib app.
So what we need it to pass the RequestContext because it's like that csrf protection works in Django.
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
def my_view(request):
c = {}
c.update(csrf(request))
# ... view code here
return render_to_response("a_template.html", c)
or
from django.views.generic.simple import direct_to_template
def app_view(request):
return direct_to_template(request, 'app_template.html', app_data_dictionary)
or
from django.shortcuts import render_to_response
from django.template import RequestContext
def app_view(request):
return render_to_response('app_template.html',
app_data_dictionary,
context_instance=RequestContext(request))
Also the documentation speaks about : extras/csrf_migration_helper.py script.
Seems to be helpful for your case :)
Hope it helps ;)
I've run in to the following Django template context processor problem.
The context processor is defined in myapp/context_processors.py:
def my_context_processor(request):
return {
'foo': 123,
}
It is wired up in settings.py along with the standard Django context processors:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'myproject.myapp.context_processors.my_context_processor',
)
The problem I'm encountering is that my_context_processor is not applied for all requests.
It is not applied for the following code:
def index(request):
return render_to_response("index.html", locals())
However, it is applied for the following code:
def index(request):
return render_to_response("index.html", locals(), context_instance=RequestContext(request))
I was under the impression that context processors are applied for ALL requests, not just when context_instance is provided.
How do I make my context processors being applied for ALL requests?
You have answered your own question. It's applied to the responses that use RequestContext. It's not applied to the ones that don't.
The way to get it to be applied to all responses is to make sure you always use RequestContext. Or, in Django 1.3+, you can use the new render shortcut instead of render_to_response, which creates a RequestContext for you.
Django introduced a new render shortcut in Django 1.3 which automatically includes the RequestContext
from django.shortcuts import render
def my_view(request):
# View code here...
context = {
'some_extra_var_for_template': 'value'
}
return render(request, 'myapp/index.html', context)
You can read about it in the Django docs.
Context processor variables are only available when sending a RequestContext object (initialized with the current request) to the template as the context_instance.