Difference between 2 identical codes - python

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.

Related

why does my form validation not work in django

I am trying to make it so that if the user already exists then log in the user else return error message. I read the documentation and implemented it into my own project. I get error: "The view sign_in.views.sign_in didn't return an HttpResponse object. It returned None instead."
from django.shortcuts import render, redirect
from .forms import SignInForm
from django.contrib.auth import authenticate, login
from django.contrib import messages
def sign_in(request):
if request.method == "POST":
form = SignInForm(request.POST)
else:
form = SignInForm()
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect("boom-home")
messages.success(request, f"Signed in as {user}")
else:
return messages.error(request, f"Failed to sign in as {user}.")
context = {
"form": form
}
return render(request, "sign_in/sign_in.html", context)
NOTE: usually this error is because people do not put "return" before the "render" method but I do put return.
I solved this problem by adding the following lines
In the following link you can see more about this problem
The view didn't return an HttpResponse object. It returned None instead
def sign_in(request):
if request.method == "POST":
form = SignInForm(request.POST)
if form.is_valid(): <---Add (Example)
return redirect('home')<---Add (Example)
else:
form = SignInForm()

Django user authentication does not work, how can I fix my login?

I am using the django-email-verification app and I had to change how a User is signed up but I left the login authentication part the same. Every time I try to login it does not allow me to sign in and says that the credentials are wrong. Also I used emails as usernames. I'm thinking its the:
user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
that needs to be changed. Please how do I fix the login?
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib.auth import get_user_model
from django_email_verification import sendConfirm
def signup(request):
if request.method == 'POST':
if request.POST['pass1'] == request.POST['pass2']:
try:
user = User.objects.get(username=request.POST['username'])
return render(request, 'accounts/signup.html', {'error': 'Email is already registered'})
except User.DoesNotExist:
'''user = User.objects.create_user(request.POST['username'], password=request.POST['pass1'])
auth.login(request, user)'''
user = get_user_model().objects.create(username=request.POST['username'], password=request.POST['pass1'], email=request.POST['username'])
sendConfirm(user)
return redirect('home')
else:
return render(request, 'accounts/signup.html', {'error': 'Passwords must match'})
else:
return render(request, 'accounts/signup.html')
def login(request):
if request.method == 'POST':
user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
if user is not None:
auth.login(request, user)
return redirect('home')
else:
return render(request, 'accounts/login.html',{'error':'username or password is incorrect.'})
else:
return render(request, 'accounts/login.html')
def logout(request):
if request.method == 'POST':
auth.logout(request)
return redirect('home')
The problem is not with authenticating, but with creating the user. Passwords are normally hashed. The .create(…) function [Django-doc] will not hash these, you can make use of .create_user(…) [Django-doc] instead:
user = get_user_model().objects.create_user(
username=request.POST['username'],
password=request.POST['pass1'],
email=request.POST['username']
)
The .create_user(…) function is a function the manager of the user model normally should provide. This will for (most) user models store the hash of the password in the database.

RecursionError in views.py django

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.

Calling "return render" won't work when calling from an outside method (Django, views.py)

Very first question here.
I am having trouble creating a reusable method to use in my views.py file for handling user authentication. I have created and imported a utils.py file that looks like this:
from django.shortcuts import render
from django.contrib.auth.forms import AuthenticationForm
def check_log_in(request):
username = None
if request.user.is_authenticated():
user = request.user
if user.is_staff == False:
message = "You are not an authorized staff member."
form = AuthenticationForm()
context = {'form': form,
'message': message}
return render(request, 'obits/login.html', context)
else:
message = "Please log-in to add a new record."
form = AuthenticationForm()
context = {'form': form,
'message': message}
return render(request, 'obits/login.html', context)
If I put this same code directly into my view, it works just fine, but now that I have it as a separate method, it doesn't break at the return render and instead continues on through the code. I used print statements to test that it was calling correctly and it is. Here is the current view:
def new(request):
check_log_in(request)
if request.method == 'POST':
if form.is_valid():
#code, yada, yada, context
return render(request, 'obits/detail.html', context)
else:
#code, yada, yada, context
return render(request, 'obits/new.html', context)
else:
#code, yada, yada, context
return render(request, 'obits/new.html', context)
In this current set-up, it will detect that the user is not logged-in, but still just go right ahead and display the new.html page, rather than redirecting to log-in. But if I cut and paste the exact code contained in check_log_in instead of just calling it, it works fine.
Any ideas? Thank you in advance!
If you return from check_log_in() but do nothing with the returned value, execution of your new() view is going to continue.
You need to check if check_log_in() returned something and if it did, return that from your new() view:
def new(request):
response = check_log_in(request)
if response is not None:
return response
if request.method == 'POST':
# rest of your code

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.

Categories