This is my views.py code.
from __future__ import unicode_literals
from django.template import RequestContext
from django.shortcuts import render_to_response
def index(request):
context = RequestContext(request)
context_dict = {'bold-message': "I am bold font from the context"}
return render_to_response('rango/index.html', context_dict, context)
After starting the project when I run this in server, I am getting the following exception.
Global name 'rendor_to_response' is not defined
Please tell what I did wrong.
rendor_to_response is a typo. It should be render_to_response.
However, you shouldn't be using render_to_response at all. You should use the render shortcut instead.
from django.shortcuts import render
def index(request):
context_dict = {'bold-message': "I am bold font from the context"}
return render(request, 'rango/index.html', context_dict)
If you are following a tutorial that is using render_to_response then it is out of date. You should switch to an updated version of the tutorial, or a different tutorial.
Related
I have two views.
class IndexView(TemplateView):
template_name = 'index.html'
#require_POST
#login_required
def partial_view(request):
return render(request, 'partials/stuff.html')
I want the index page to be "public" but if user takes action (which triggers partial view), they should be redirected to LOGIN_URL, if not logged in.
The problem is that my partial view will return the entire LOGIN_URL page. So there's a page within a page now.
Is it possible to redirect the "parent" page when using partial views?
I didn't manage to make "post-login redirection" work but my solution is good enough for my needs.
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.conf import settings
from django.contrib.auth.decorators import login_required as django_login_required
from django.http import HttpResponse
from functools import wraps
from django.shortcuts import resolve_url
def login_required(function=None, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
#wraps(function)
def wrapper(request, *args, **kwargs):
if not request.user.is_authenticated and request.htmx:
resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
return HttpResponse(status=204, headers={'HX-Redirect': resolved_login_url})
return django_login_required(
function=function,
login_url=login_url,
redirect_field_name=redirect_field_name
)(request, *args, **kwargs)
return wrapper
I want to change the return url of a django-allauth page.
I know I could override the entire function in views.py and just change the return url at the bottom, but doesn't seem ideal as it could cause issues if associated code in the django-allauth package gets changed by the packages authors.
Is there a better way to do this?
Thank you.
How I ended up doing this:
from allauth.account.views import PasswordChangeView
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse
class CustomPasswordChangeView(LoginRequiredMixin, PasswordChangeView):
def get_success_url(self):
if [...]:
success_url = reverse([...], kwargs={'username': self.request.user.username})
else:
success_url = reverse([...], kwargs={'username': self.request.user.username})
return success_url
custom_password_change = login_required(CustomPasswordChangeView.as_view())
All my views are being rendered properly but when i try to render a list using iteration nothing is displayed on the page, without error.
the view:
from django.shortcuts import render
from haleys_chemist.models import anti_bacterials
from django.http import HttpResponse
from .table import anti_bacterials_Table
from django_tables2 import RequestConfig
from datetime import datetime
from django.http import HttpResponseRedirect
from .forms import notepadform
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView,ListView
class retriever(TemplateView):
template_name='index.html'
def expiry_days(self,request):
expired_drugs= anti_bacterials.objects.all()
args={'expired_drugs':expired_drugs}
return render (request, self.template_name,args)
template(index.html):
<h6><i>Drugs about to expire</i></h6>
{%for expired_drug in expired_drugs%}
<ul>
<li>{{expired_drug.Drug_name}}</li>
<li>{{expired_drug.expiry_date}}</li>
</ul>
{%endfor%}
</div>
model:
class anti_bacterials(models.Model):
Drug_id= models.IntegerField(primary_key=True);
Drug_name= models.CharField(max_length=50);
expiry_date= models.DateField();
Price_per_mg= models.DecimalField(decimal_places=2, max_digits=20)
i need to list the expired drugs on the left bar. i know i have queried for all objects on the view but still i should get a list of all the objects names and expiry dates.
You are not using the generic TemplateView properly.
The method expiry_days will never be called because the generic TemplateView doesn't know about it.
Simply you can use the method get_context_data to achieve what you want:
class retriever(TemplateView):
template_name='index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['expired_drugs']= anti_bacterials.objects.all()
return context
Read more about the generic TemplateView in Django's official documentation and here.
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.
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 ;)