I have a registration view in django like this:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response, RequestContext, HttpResponseRedirect
def register(request):
'''Registers the users'''
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect('/index/') #Returns user to user if successfully logs in
else:
form = UserCreationForm() #Redirects to the UserCreationForm is the form is invalid
return render_to_response('registration/register.html', {'form':form}, context_instance=RequestContext(request))
else:
return render_to_response('registration/register.html', {'form':form}, context_instance=RequestContext(request))
When I try to run the view I get UnBound LocalError.
#Full exception:
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/zurelsoft/workspace/fyp/summary/views.py" in register
20. return render_to_response('registration/register.html', {'form':form}, context_instance=RequestContext(request))
Exception Type: UnboundLocalError at /
Exception Value: local variable 'form' referenced before assignment
What's wrong?
If Method is not post then form is going to the last else block
you should define your form outside the request.POST like
def register(request):
'''Registers the users'''
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect('/index/') #Returns user to user if successfully logs in
else:
form = UserCreationForm() #Redirects to the UserCreationForm is the form is invalid
return render_to_response('registration/register.html', {'form':form}, context_instance=RequestContext(request))
else:
return render_to_response('registration/register.html', {'form':form}, con
For GET requests you are not defining form.
I would suggest to add
form = UserCreationForm()
before line
if request.method == 'POST':
Related
I'am trying to do a website and I have problem with uploading the file. On admin site I can upload and import any file but when I create view, I get this:
"The view main.views.licz didn't return an HttpResponse object. It returned None instead."
Here is the code from main.models:
class Plik(models.Model):
file = models.FileField(upload_to='uploads/')
Code from forms.py:
class upload(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
And code from views.py:
def licz(request):
if request.method == "POST":
form = upload(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect("main/licz.html", {"form":form})
else:
form = Plik()
return render(request, "main/licz.html", {"form":form})
Plz I am trying to solve this like 5 days...
def licz(request):
if request.method == "POST":
form = upload(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect("main/licz.html", {"form":form})
else:
form = Plik()
return render(request, "main/licz.html", {"form":form})
# if request is GET, python will execute this part of the function
Your livz function does not return anything on a GET request.
If no return statement is given, Python will return None.
The return render(...) is only executed on a POST request (when the form is submitted) with invalid form.
You need to also render your page on other request method.
A typical form view should look like the following (pay attention to the indent):
def form_view(request):
if request.method == 'POST':
form = MyForm(data=request.POST)
if form.is_valid():
# do stuff with the form
return HttpResponseRedirect('/success-url')
else:
form = MyForm()
return render('my-template', {'form': form})
Pay attention to your conditions (if/else/...) and make sure your page return a response in every possible path the code execution takes.
def licz(request):
if request.method == "POST":
form = upload(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect("main/licz.html")
else:
form = Plik()
return render(request, "main/licz.html", {"form":form})
I have a vĂews to display and save a form as below:
#login_required(login_url='/login') # Check login
def addlisting(request):
if request.method == 'POST':
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ProductForm()
return render(request, 'listing/addlisting.html', {
'form': form
})
But When I load the html file I got this error
ValueError at /addlisting
The view listing.views.addlisting didn't return an HttpResponse object. It returned None instead.
Request Method: GET
Request URL: http://127.0.0.1:8000/addlisting
Django Version: 3.2.3
Exception Type: ValueError
Exception Value:
The view listing.views.addlisting didn't return an HttpResponse object. It returned None instead.
Exception Location: C:\Users\Daisy\OneDrive\Documents\Work\django\shecodes\bookapp\env\lib\site-packages\django\core\handlers\base.py, line 309, in check_response
Python Executable: C:\Users\Daisy\OneDrive\Documents\Work\django\shecodes\bookapp\env\Scripts\python.exe
Python Version: 3.8.2
Python Path:
['C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\bookapp',
'C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\env\\Scripts\\python38.zip',
'c:\\users\\daisy\\appdata\\local\\programs\\python\\python38\\DLLs',
'c:\\users\\daisy\\appdata\\local\\programs\\python\\python38\\lib',
'c:\\users\\daisy\\appdata\\local\\programs\\python\\python38',
'C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\env',
'C:\\Users\\Daisy\\OneDrive\\Documents\\Work\\django\\shecodes\\bookapp\\env\\lib\\site-packages']
Server time: Sun, 30 Jan 2022 07:41:40 +0000
Please take a look.
Thanks in advance !!!!!!!!!!!!!!!!!!!!
Are you sure you are using POST method?
Please try it out:
#login_required(login_url='/login') # Check login
def addlisting(request):
if request.method == 'POST':
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ProductForm()
return render(request, 'listing/addlisting.html', {'form': form})
return redirect('home')
NOTE: Just trying to get with the error. please just check it out that you are redirected to home. if you get to the home that means you are not using the POST method as well.
Yep that is the error: Request Method: GET
you are using GET. please send the request using POST method.
Good idea to use:
from django.views.decorators.http import require_http_methods
#require_http_methods(["POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
# ...
pass
please read more about using decoratos to allow the method you want on your function: https://docs.djangoproject.com/en/4.0/topics/http/decorators/
this may help you:
from django.views.decorators.http import require_http_methods
#require_http_methods(["POST"])
#login_required(login_url='/login') # Check login
def addlisting(request):
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
form = ProductForm()
return render(request, 'listing/addlisting.html', {'form': form})
There is not else part in your views.py so while rendering page GET request is called and because of that it throws didn't return an HttpResponse object. So add else part and render your ProductForm as
#login_required(login_url='/login') # Check login
def addlisting(request):
if request.method == 'POST':
form = ProductForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ProductForm()
return render(request, 'listing/addlisting.html', {'form': form})
else: #<------------ add else part here which will `render` your form
form = ProductForm()
return render(request, 'listing/addlisting.html', {'form': form})
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, f'Your account has been created. Log In to continue.')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
This is the code when I run it I get an error. But that error shouldn't be there since I am not overriding the the save() method. please help.
try to get each form input one by one and then save the form. for example:
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
data = YourModelName()
data.input1 = form.cleaned_data['input1']
data.input2 = form.cleaned_data['input2']
# ...
form.save()
messages.success(request, 'Your account created. You can now Login.')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
I have a feeling that you are doing Corey Schafer's Django tutorial. If so, other users have had the same problem, which is discussed here:
Django - TypeError - save() got an unexpected keyword argument 'force_insert'
The issue lies in overriding the save method in your Profile model
im currently facing the problem that i want to call a view from another app (accounts app which holds the user model) within my main app (a blog app).
this is the error i get:
django.core.exceptions.FieldError: Unknown field(s) (username) specified for User
urls.py
...
from quickblog import views as core_views
from accounts import views as views_accounts
...
url(r'^myaccount/$', views_accounts.view_profile, name='myaccount'),
views.py (accounts app):
from django.shortcuts import render, redirect
from django.urls import reverse
from accounts.forms import (
RegistrationForm,
EditProfileForm
)
from django.contrib.auth.models import User
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect(reverse('accounts:home'))
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'reg_form.html', args)
def view_profile(request, pk=None):
if pk:
user = User.objects.get(pk=pk)
else:
user = request.user
args = {'user': user}
return render(request, 'profile.html', args)
def edit_profile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect(reverse('accounts:view_profile'))
else:
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'edit_profile.html', args)
def change_password(request):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return redirect(reverse('accounts:view_profile'))
else:
return redirect(reverse('accounts:change_password'))
else:
form = PasswordChangeForm(user=request.user)
args = {'form': form}
return render(request, 'change_password.html', args)
This is my first django app, is there maybe anything i need to know about linking two apps within one project?
thanks
I'm trying to login using a form setup here -
http://stackoverflow.com/questions/31576801/django-login-exception-value-unicode-object-is-not-callable#31576801
When clicking login I get the following traceback -
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/datapi/core/views.py" in LoginRequest
47. return render_to_response('/',ctx,context_instance=RequestContext(request))
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py" in render_to_response
23. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
170. t = get_template(template_name, dirs)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in get_template
144. template, origin = find_template(template_name, dirs)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in find_template
136. raise TemplateDoesNotExist(name)
Exception Type: TemplateDoesNotExist at /login/
Exception Value: /
This is my view -
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(email=email, password=password)
if user is not None:
login(request, user)
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
else:
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
else:
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
else:
form = LoginForm()
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
I can only imaging the template doesn't exist because it's not a template. what I'm trying to do is get my view to login and then just return me to the root url.
You need to pass a template_name in render_to_response. You are not doing that but instead passing a url.
Basic signature of render_to_response:
render_to_response(template_name[, context][, context_instance][, content_type][, status][, dirs][, using])
This will render a given template with a given context dictionary and returns an HttpResponse object with that rendered text.
So below statement should not be:
return render_to_response('/', {'form': form}, context_instance=RequestContext(request))
but instead be something like:
return render_to_response('template_name_of_index_page', {'form': form}, context_instance=RequestContext(request))
I had to revert to the following view -
def LoginRequest(request):
active = "index"
message = ""
if request.user.is_authenticated():
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
else:
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['email']
password = form.cleaned_data['password']
user = authenticate(username=username,password=password)
if user is not None and user.is_active:
login(request,user)
return HttpResponseRedirect('/dashboard')
else:
message = "user and/or password incorrect"
ctx = {'active':active, 'form': form}
return render_to_response('index.html',ctx,context_instance=RequestContext(request))
and now no issues.