RecursionError in views.py django - python

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.

Related

MultiValueDictKeyError at /form 'name1'

I am new at django
I was designing my own website to store value of form in the database
please help
I can't able to overcome the error
the error is multivaluedicterror
from django.shortcuts import render
from django.http import HttpResponse
from main.models import recieve_content
# Create your views here.
def index(request):
return render(request,'index.html')
def about(request):
return render(request,'about.html')
def contact(request):
return render(request,'contact.html')
def donation(request):
return render(request,'donation.html')
def form(request):
if request.method=="POST":
name1=request.POST["name1"]
name2=request.POST["name2"]
address=request.POST["address"]
content=request.POST["content"]
data=recieve_content(fname=name1,lname=name2,address=address,content=content)
data.save()
return HttpResponse("your data saved successfully")
return render(request,'form.html')

Difference between 2 identical codes

I'm am trying to troubleshoot an HTTP response one code works fine but, the other one is returning an ValueError they are the both same code and I looked over them for 1hr side by side but, I can't find what is wrong with the bad code this is really bugging me.
Working code:`
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import auth
def signup(request):
if request.method == 'POST':
if request.POST['password1'] == request.POST['password2']:
try:
user = User.object.get(username=request.POST['username'])
return render(request, 'accounts/signup.html', {'error':'Username in use'})
except User.DoesNotExist:
User.objects.create_user(request.POST['username'], password=request.POST['password1'])
auth.login(request.user)
return redirect('home')
else:
return render(request, 'accounts/signup.html')
def login(request):
return render(request, 'accounts/login.html')
def logout(request):
return render(request, 'accounts/signup.html')
BAD CODE:
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import auth
def signup(request):
if request.method =='POST':
if request.POST['password1'] == request.POST['password2']:
try:
user = User.object.get(username=request.POST['username'])
return render(request, 'accounts/signup.html', {'error':'Username in use '})
except User.DoesNotExist:
User.objects.create_user(request.POST['username'], password=request.POST['password1'])
auth.login(request.user)
return redirect('home')
else:
return render(request, 'accounts/signup.html')
def login(request):
return render(request, 'accounts/login.html')
def logout(request):
return render(request, 'accounts/signup.html')
`
else:
return render(request, 'accounts/signup.html')
So this piece of code if it's not a post, but a GET request in the first piece of code it will return the web page signup.html. But in the second the else statement isn't even under an if.

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.

Django login part

I am now working on a system using the Django framework. I am writing the user login part. It seems successful but it doesn't work very well.
The login system can recognise the user by his/her username and password.
The authentication could only last for one "webpage". When I loaded another page or even reloaded the page, django can't get the info of the user(seems logged out)
If I looked at the page resources, I saw a session number made after the login process.
What should I do to ensure only one login is needed? And keep my user logged in during the whole process?
Here is my view file
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext, loader
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render_to_response,redirect
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.template.context_processors import csrf
from . import models
from . import form as f
from django.contrib.sessions.backends.db import SessionStore
def index(request):
if request.user != None :
template = loader.get_template('index.html')
return HttpResponse(template.render(None))
else :
return HttpResponseRedirect('/PDT/login_failed')
def Home(request):
template = loader.get_template('Home.html')
return HttpResponse(template.render(None))
def loggin_in(request):
c = {}
c.update(csrf(request))
return render_to_response('login.html', c)
def login_user(request):
logout(request)
username = password = ''
if request.POST:
username = request.POST.get('username','')
password = request.POST.get('password','')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
request.session['username']=user.username
return HttpResponseRedirect('/PDT/logged_successful')
return HttpResponseRedirect('/PDT/inactive')
return HttpResponseRedirect('/PDT/incorrect')
return HttpResponseRedirect('/PDT/login_failed')
def logged_in(request):
if request.user :
return render_to_response('index.html',{ 'user' : request.user },context_instance=RequestContext(request))
else :
return HttpResponseRedirect('/PDT/login_failed')
def login_failed(request):
return render_to_response('problem.html',{ 'message' : "Login failed" })
def log_out(request):
request.session.flush()
logout(request)
return render_to_response('problem.html',{ 'message' : "Logged out" })
def inactive(request):
return render_to_response('problem.html',{ 'message' : "Inactive" })
def incorrect(request):
return render_to_response('problem.html',{ 'message' : "Incorrect Username or Password" })
def iter_update(request):
if request.session['username'] != None :
return render_to_response('iter_update.html',{ 'user' : request.user },context_instance=RequestContext(request))
else :
return HttpResponseRedirect('/PDT/login_failed')
def Create_form(request):
if request.method == "POST":
form = f.ProjectForm(request.POST)
if(form.is_valid()):
print(request.POST['title'])
form.save()
message = 'success'
else:
message = 'fail'
return render_to_response('Create_form.html',
{'message': message,
'user': request.user,},
context_instance=RequestContext(request))
else:
return render_to_response('Create_form.html',
{'form': f.ProjectForm()},
context_instance=RequestContext(request))
Please use return render(request, template_name, context_dict) to render templates. Your peculiar way probably strips it of context.
Also, take a look at this decorator, and use it instead of your current if request.user != None : statements.
Your user is logged in, but because you are strangely rendering the Home and Index templates via template.render(None), there is no request or user context in your template. Instead, use the render shortcut which runs context processors.

"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')

Categories