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.
Related
This is throwing me a recursion error.
It first suggested that I put in the argument 'request' in the signup() but then I received a new error.
Here is my code:
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from .forms import signup
from django.utils.html import format_html
from django.contrib import messages
from .models import signup
def index(request):
return render(request, 'myapp/index.html')
def signup(request):
if request.method == 'POST':
register_form = signup(request.POST)
if register_form.is_valid():
post = register_form.save()
message = format_html("Hi {0}, Thank you for signing up with us! See your profile <a href=''>{1}</a>".format(register_form.cleaned_data['name'], "here"))
return render(request, 'myapp/register.html', {'signup':register_form, 'message': message})
else:
message = register_form.errors
form = signup(request)
return render(request, 'myapp/register.html', {'signup':form, 'message': message})
else:
form = signup(request)
return render(request, 'myapp/register.html', {'signup':form})
throws:
if request.method == 'POST': RecursionError: maximum recursion depth
exceeded in comparison
Your problem are these lines
...
from .models import signup
...
def signup(request):
...
if request.method == 'POST':
register_form = signup(request.POST)
...
You're redefining signup() causing it to call itself indefinitely. You'll need to rename one of these methods.
I have a form that is filled out on a webpage. The goal of the form is to gather some basic info, and then save the IP of the sender to the DB too. The form submits a POST request to my Django view, but Django gives me the error:
if request.method() == 'POST':
TypeError: 'str' object is not callable
Here is the view:
from .form import SignUpForm
from django.shortcuts import render
from django.http import HttpResponseRedirect
def index(request):
if request.method() == 'POST':
form = SignUpForm(request.POST)
if form.is.valid():
signup_item = form.save(commit=False)
signup_item.ip_address = request.META['HTTP_X_FORWARDED_FOR']
signup_item.save()
return HttpResponseRedirect(request.path)
else:
form = SignUpForm()
return render(request, 'index.html', {'form': form})
Here is the urls.py
from django.conf.urls.import url
from django.contrib import admin
from form import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', views.index, name='home')
]
I think the issue is with request.method(); method is a string data member, not a member function. Remember - this is python, where 'getters' are often dropped in favor of directly accessing class members.
So, try:
if request.method == 'POST':
form = SignUpForm(request.POST)
etc.
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))
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')
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