Passing values from views.py to a template - django

Maybe this is a very silly question, but I'm new to django.
My application doesn't require the use of any database, so my models.py is empty.My application receives a POST request from a template which is handled in my views.py and the response is another template.How can I pass values from views.py to my new template (Without using the database)?
My views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
def search_isbn(request):
if request.method == 'POST':
x=500
return render_to_response('results.html',RequestContext(request))
I wish to pass the value x to results.html.How can I do that ?
Any help would be appreciated. Thanks in Advance.

Pass a dictionary that contains the variables you want to pass.
def search_isbn(request):
x = 0 # Without this, you will get NameError if request.method is not 'POST'
if request.method == 'POST':
x = 500
return render_to_response('results.html', RequestContext(request, {'x': x}))
# ^^^^^^^^

Also you can use render function.
from django.shortcuts import render
def search_isbn(request):
x = 0
if request.method == 'POST':
x=500
return render('results.html', {'x':x})

Related

The view formApp.views.formRegister didn't return an HttpResponse object

Views.py
from django.shortcuts import render
from . models import Registerform
# Create your views here.
def formRegister(request):
if request.method == 'POST':
if request.POST.get('firstN') and request.POST.get('lastN') and request.POST.get('Email') and request.POST.get('pass'):
Registerform = Post()
Registerform.firstName = request.POST.get('firstN')
Registerform.lastName = request.POST.get('lastN')
Registerform.email = request.POST.get('Email')
Registerform.password = request.POST.get('pass')
Registerform.save()
return render(request, 'formApp/formreg.html', context_instance=RequestContext(request))
As you can see in the above error image, my code is not functioning properly. I have added my models.py and views.py code. Please help me to resolve the issue.
Why it doesn't work
Every django view, has to return a valid HttpResponse object (as the error message says). That is this part of your code:
return render(request, 'formApp/formreg.html', context_instance=RequestContext(request))
The render function is a shortcut which will return such an object.
The problem though is that, all of this is wrapped inside an if request.method == 'POST':, and so if the request is something that is not a POST, the function just returns nothing. Hence the error
How to fix it
As you can see in the screen shot you've provided, the request method is a GET, so you need to add some code to deal with the case of a GET request.
Add something like this:
if request.method == "GET":
return render(...) # put what you want here

The view posts.views.create didn't return an HttpResponse object. It returned None instead

having problem with my posts.view page
this is my views page but the error still keeps on coming that not httpresponse
Try it:
def create(request):
if request.method == 'POST':
# Your code here
return render(request, 'posts/home.html')
def home(request):

Mocking forms in view unit tests

I can't seem to be able to mock the behaviour of a form when unit testing views.
My form is a simple ModelForm and resides in profiles.forms. The view is (again) a simple view that checks whether the form is valid and then redirects.
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from profiles.forms import ProfileForm
def home(request):
form = ProfileForm()
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid():
profile = form.save()
return HttpResponseRedirect(reverse("thanks"))
My test looks like this:
class TestViewHomePost(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_form(self):
with mock.patch('profiles.views.ProfileForm') as mock_profile_form:
mock_profile_form.is_valid.return_value = True
request = self.factory.post(reverse("home"), data={})
response = home(request)
logger.debug(mock_profile_form.is_valid.call_count) # "0"
is_valid is not being called on the mock, which means ProfileForm is not patched.
Where did I make a mistake?
I was able to fix mocking is_valid as following:
def test_form(self):
with mock.patch('profiles.views.ProfileForm.is_valid') as mock_profile_form:
mock_profile_form.return_value = True
request = self.factory.post(reverse("home"), data={})
response = home(request)
note: and you could use mock_profile_form.assert_called_once() to check if the mock has been called.

Set cookie in django-cms plugin

Using Django 1.5.5, Django-CMS 2.4.2
I wrote a plugin for django-cms *(cms.plugin_base.CMSPluginBase)*. Plugin create a some form, that works fine. But I get a problem - after submitting a form - how can I set a cookie ?
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from poll.models import PagePoll
from poll.forms import PollForm
from django.http import HttpResponse
class PollPlugin(CMSPluginBase):
""" upload a poll """
model = PagePoll
name = u'Poll'
render_template = u"plugins/page_poll.html"
def render(self, context, instance, placeholder):
#upload poll form
request = context['request']
form = PollForm(instance.poll, request.POST)
#validate the form
if request.method == 'POST':
if form.is_valid():
form.save()
#=SAVE COOKIES HERE=
else:
form = PollForm(instance.poll)
context['form'] = form
return context
plugin_pool.register_plugin(PollPlugin)
The answer was found here:
https://djangosnippets.org/snippets/2541/
The problem was that cms-plugin can't return a responce object, where cookies need to bet set... So the trick is to throw a custom exception with HttpResponceRedirect

Django View Value Error

I'm hitting a wall with this error. I'm sure I'm overlooking something basic, just can't seem to figure it out...
ValueError at /sing/register
The view sing.singer.views.grade didn't return an HttpResponse object.
the view file...
from django.shortcuts import render_to_response
from django import forms
from django.http import HttpResponseRedirect
from django.template import Template, RequestContext
from dash.forms import GradeForm
def register(request):
if request.method == 'POST':
form = GradeForm(data=request.POST)
if form.is_valid():
new_dash_profile = form.save()
new_user = form.save()
return HttpResponseRedirect("/success/")
else:
form = RegisterForm()
return render_to_response('grade.html',{'form':form},context_instance=RequestContext(request) )
my urls.py
urlpatterns = patterns('dashboard.dash.views',
(r'^sing/register','register' ),)
my settings.py
TEMPLATE_DIRS = (
"/home/django/testing/sing/grade/templates",)
def register(request):
if request.method == 'POST':
form = GradeForm(data=request.POST)
if form.is_valid():
new_dash_profile = form.save()
new_user = form.save()
return HttpResponseRedirect("/success/")
else:
form = RegisterForm()
return render_to_response('grade.html',{'form':form},context_instance=RequestContext(request) )
your indents look off?
Initially you are entering the view with request != 'POST' which will never reach that else statement at the bottom, so you dont get a HttpResponse.
The other thing that looks strange is even if you fix your indents, you show the RegisterForm initially, and after the post request, you put the data from your RegisterForm into a GradeForm, if that doesn't validate you show pass your GradeForm to your template. Is this what you intended?
also in your urls.py I would add / to:
(r'^sing/register','register' ),)
like:
(r'^sing/register/','register' ),)
unless you want it to match (for example):
www.site.com/sing/registerasdf/
i might even suggest using '/$' at the end like this:
(r'^sing/register/$','register' ),)
to prevent matches to (for example):
www.site.com/sing/register/asdf/asdf/asdf/
www.site.com/sing/register/asdf/asdf/
www.site.com/sing/register/asdf/
Judging from the code, the only time it does not return a HttpResponse is when it's not a POST request. Maybe you are doing a GET instead?
I think its your HttpResonseRedirect. I can't say I've used it that often (if at all). If I were you I would try shortcut redirect
http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#redirect