global name 'localset' is not defined - python

I get this error.
global name 'localset' is not defined
Following is my code.
from django.shortcuts import render, render_to_response, RequestContext
from forms import SignUpForm
# Create your views here.
def home(request):
form= SignUpForm(request.POST or None)
if form.is_valid():
save_it=form.save(commit=False)
save_it.save()
return render_to_response("signup.html", localset, context_instance= RequestContext(request))

In the last line of code:
return render_to_response("signup.html", localset, context_instance= RequestContext(request))
The variable localset is not defined.

#Amin A answer is correct for your original question. You do have a variable set within the render_to_response function which is not defined within your view function.
You should change the render_to_response line to look like this:
return render_to_response(
'signup.html', context_instance=RequestContext(request)
)
There is something which you should be aware of here also. According to the django documentation the use of context_instance has been deprecated since django 1.8.
Deprecated since version 1.8:
The context_instance argument is deprecated. Use the render() function instead which always makes RequestContext available.
You should now be using the render() function if you are passing back a context.
This will now mean you code will look something like this:
from django.shortcuts import render
from forms import SignUpForm
# Create your views here.
def home(request):
form= SignUpForm(request.POST or None)
if form.is_valid():
save_it=form.save(commit=False)
save_it.save()
return render(request, "signup.html")

from django.shortcuts import render, render_to_response, RequestContext
from forms import SignUpForm
Create your views here.
def home(request):
form= SignUpForm(request.POST or None)
if form.is_valid():
save_it=form.save(commit=False)
save_it.save()
return render_to_response("signup.html", locals(), context_instance= RequestContext(request))

Related

Passing context to a Response and using it in a view

I am working on a web app and I want to use HttpResponse or HttpResponseRedirect instead of render. But I dont know hoe to pass context in response as it does not have context parameter like render. And also how to use the passed context in the url or view ?
Here is my view:
#login_required
def view_task_description(request):
if request.method == 'POST':
task_description = GetTaskDescription(data=request.POST, user=request.user)
if task_description.is_valid():
obj = GetTaskDescription.get_task_description(task_description)
return render(request, 'todoapp/task_desc.html', context={'description': obj[0].description})
return render(request, 'todoapp/select_task_description.html', context={'view_tasks': GetTaskDescription(user=request.user)})
I want to use Redirect or ResponseRedirect with the context instead of the render that I am returning if my form is valid. Basically render still shows the response as a POST method and I want the response to be a GET. How can I do so ? Thanks.
You can simply create a new view for that. Then link it to the existing view using redirect. For example:
# view
from django.shortcuts import get_object_or_404
#login_required
def get_task_description(request, pk):
obj = get_object_or_404(TaskDescriptionModel, pk=pk)
return render(request, 'todoapp/task_desc.html', context={'description': obj.description})
# url
url(r'^some_path/(?P<pk>[0-9]+)/$', get_task_description, name="get_task_description")
# linking to existing view
from django.shortcuts import redirect
...
if task_description.is_valid():
obj = GetTaskDescription.get_task_description(task_description)
return redirect('get_task_description', pk=obj[0].pk) # <-- Pointing the new view

undefined name in function 'redirect'

any advice on whats the problem? Im learning from a Django v1 tutorial, ive had a look at the documentation but cannot figure it out.
imports:
from django.shortcuts import render
from accounts.forms import RegistrationForm
from django.contrib.auth.forms import UserChangeForm
function:
def edit_profile(request):
if request.method == 'POST':
form = UserChangeForm(request.POST instance=request.user)
if form.is_valid():
form.save()
return redirect('/account/profile')
else:
form = UserChangeForm(instance=request.user)
args = {'form': form}
return render(request, 'accounts/edit_profile.html', args)
thanks
You need to import redirect from django.shortcut with
from django.shortcuts import redirect
This is well documented in the Django's shortcut documentation.

"The view didn't return an HttpResponse object"

This is the error I am getting: The view extraio.file_uploader.views.Upload_File didn't return an HttpResponse object.
Can anyone see what I'm doing wrong here? I can't seem to figure out why I would be getting that exception since I am returning an HttpResponseRedirect.
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from models import Files
from forms import Upload_File_Form
def Upload_File(request):
if request.method == 'POST':
form = Upload_File_Form(request.POST, request.FILES)
if form.is_valid():
for f in request.FILES.get_list('file'):
f.save()
orgfilename = Files(orgname=f.name)
orgfilename.save()
return HttpResponseRedirect('success.html')
else:
form = Upload_File_Form()
return render_to_response('upload.html', {'form': form})
You returning your HttpResponse object only on POST request.
Rewrite your view like this
def Upload_File(request):
form = Upload_File_Form(request.POST or None,
request.FILES or None)
if request.method == 'POST':
if form.is_valid():
for f in request.FILES.getlist('file'):
f.save()
orgfilename = Files(orgname=f.name)
orgfilename.save()
return HttpResponseRedirect('success.html')
return render_to_response('upload.html', {'form': form},
context_instance=RequestContext(request))
EDIT: BTW you forgot to set context_instance in you render_to_response
Also you can use render instead
render(request, 'upload.html', {'form': form})
request.FILES.get_list('file') should be request.FILES.getlist('file')

csrf token Follow up

Hello and thank you in advance. This is a follow up question from the following thread (not sure if I should have posted there or started a new thread...:
CSRF token missing or incorrect even though I have {% csrf_token %}
I am not sure what I need to do with the code to make csrfContext work. I am trying to use ModelForm to collect data to a model and write it to a MYSQL table. I am gettingthe error:
Reason given for failure:
CSRF token missing or incorrect.
Here is the code:
from django.shortcuts import render_to_response
from djengo.template import RequestContext
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from acmetest.models import Player
from acmetest.models import PickForm
csrfContext = RequestContext(request)
return render_to_response('makepick.html', csrfContext)
def playerAdd(request, id=None):
form = PickForm(request.POST or None,
instance=id and Player.objects.get(id=id))
# Save new/edited pick
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/draft/')
return render_to_response('makepick.html', {'form':form})
Again,
Thank you for your help!
dpbklyn
Update your code thusly:
from django.shortcuts import render
# from djengo.template import RequestContext <- this is not valid.
These two lines, as Yuji pointed out, are not valid python, and in addition they are not necessary if you use the render shortcut.
# csrfContext = RequestContext(request)
# return render_to_response('makepick.html', csrfContext)
Modify your return line:
# return render_to_response('makepick.html', {'form':form})
return render(request,'makepick.html',{'form':form})
I'm assuming we're talking about the playerAdd view - you need to pass RequestContext to the response there.
def playerAdd(request, id=None):
form = PickForm(request.POST or None,
instance=id and Player.objects.get(id=id))
# Save new/edited pick
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/draft/')
return render_to_response('makepick.html', RequestContext(request, {'form':form}))
The first lines in your code are hard to understand and doesn't even appear to be valid python. You can't use return from outside a function block.

reverse() is not working

I am trying to pass the id through reverse. But it's not working. I'm getting this error
Reverse for 'reg.views.thanks' with arguments '(20,)' and keyword arguments '{}' not found.
Here is my views.py:
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from reg.models import registration, registrationform
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
def registration(request):
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
data = form.save()
id = data.id
return thanks(request,id)
else:
form = registrationform()
return render_to_response('registration.html', {'form' : form}, context_instance=RequestContext(request))
def thanks(request, id):
p = get_object_or_404(registration, pk=id)
return render_to_response('thanks.html', {'reg' : p})
Here is my urls.py:
from django.conf.urls import patterns, include, url
url(r'^registration/$', 'reg.views.registration'),
url(r'^thanks/$', 'reg.views.thanks'),
url(r'^$','django.views.generic.simple.direct_to_template', {'template' : 'index.html'}),
)
Here is thanks.html:
<html>
<body>
<p>Thank you for registration mr.{{reg.username}}</p>
</body>
</html>
and I'm also showing my models.py:
from django.db import models
from django.forms import ModelForm
class registration(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class registrationform(ModelForm):
class Meta:
model = registration
Thanks.
from this links (django tutorial):
https://docs.djangoproject.com/en/dev/topics/http/urls/#django.core.urlresolvers.reverse
example:
def myview(request):
return HttpResponseRedirect(reverse('arch-summary', args=[1945]))
so your code goes to:
in urls.py:
url(r'^thanks/(?P<id>\d+)$', 'reg.views.thanks', name='my_thanks_url')
in your function:
return HttpResponseRedirect(reverse('my_thanks_url', args=[id]))
This line
return HttpResponseRedirect(reverse('reg.views.thanks', args=(id,)))
Is trying to construct a url to your view reg.views.thanks, with the id variable used as a parameter.
This line in urls.py
url(r'^thanks/$', 'reg.views.thanks'),
Does not have anywhere for that parameter to go.
The first thing that you need to figure out is whether you actually want to send an HTTP redirect to the browser to tell it to go to the 'thanks' page. If you really do, then you need a way to send that id in the URL. You can do it as part of the URL path itself, as #moguzalp suggests, or you can put it in the query string, like
/thanks/?id=12345
Or you can do other things, like stashing the id in the user's session, and pulling it out when they request the thanks page. That's a bit more complicated, though.
If you don't actually need to issue an HTTP redirect, then there's nothing stopping you from just calling the thanks() function from inside your view function, like this:
def registration(request):
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
data = form.save()
id = data.id
return thanks(request, id)
else:
form = registrationform()
return render_to_response('registration.html', {'form' : form}, context_instance=RequestContext(request))
The URL won't change in the browser, but the correct ID will be used, and doesn't need to appear anywhere else, in the URL, the query parameters, or the session

Categories