Django error with views for form display and save - django

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})

Related

Django, problem with render request: "The view main.views.licz didn't return an HttpResponse object. It returned None instead."

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})

save() got an unexpected keyword argument 'force_insert'

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

my django registration form doesn´t validate the data

def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid() is True:
form.save()
#log the user in
return redirect('/account')
else:
form = UserCreationForm()
args = {'form': form}
return render(request, 'accounts/reg_form.html', args)
If i try to log in it seems that it doesn't think the data is valid and i don´t know why. It just cleans the registration fields and shows the registrationsite again. I´m using Django 2.1

Django Error:: global name 'HttpRequestRedirect' is not defined

I am getting this error, I tried working on it a lot but cannot understand whats wrong.
I am basically trying to make a signup registration that has a couple of forms to be filled
Request Method: GET
Request URL: http://127.0.0.1:8000/gi/
Django Version: 1.5.1
Exception Type: NameError
Exception Value:
global name 'HttpRequestRedirect' is not defined
Exception Location: /home/xx/Desktop/GoAmma/vendorAmmma/vreg/views.py in GIRegistration, line 42
Python Executable: /home/xx/Desktop/forfte/bin/python
Python Version: 2.7.3
The view is as shown below:
# Create your views here.
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from vreg.forms import RegistrationForm, LoginForm
from vreg.models import Vendor
from django.contrib.auth import authenticate, login, logout
def VendorRegistration(request):
if request.user.is_authenticated():
return HttpRequestRedirect('/profile/')
if request.method=='POST':
form= RegistrationForm(request.POST)
if form.is_valid():
user=User.objects.create_user(username=form.cleaned_data['username'], email= form.cleaned_data['emailadd'], password= form.cleaned_data['password'])
user.save()
vreg=Vendor(user=user)
vreg.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html', {'form':form}, context_instance=RequestContext(request))
else:
''' user is not submitting form show them blank registration form'''
form= RegistrationForm()
context={'form':form}
return render_to_response('register.html', context, context_instance=RequestContext(request))
#login_required
def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
vreg= request.user.get_profile
context={'vreg':vreg}
return render_to_response('profile.html',context,context_instance=RequestContext(request))
#login_required
def GIRegistration(request):
if request.user.is_authenticated():
return HttpRequestRedirect('/profile/')
if request.method=='POST':
form= GIForm(request.POST)
if form.is_valid():
contact = form.save()
contact.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('generalinfo.html', {'form':form}, context_instance=RequestContext(request))
else:
''' user is not submitting form show them blank registration form'''
form= GIForm()
context={'form':form}
return render_to_response('generalinfo.html', context, context_instance=RequestContext(request))
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method=='POST':
form=LoginForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
password=form.cleaned_data['password']
vreg= authenticate(username=username,password=password)
if vreg is not None:
login(request,vreg)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('login.html',{'form':form}, context_instance= RequestContext(request))
else:
return render_to_response('login.html',{'form':form}, context_instance= RequestContext(request))
else:
'''user not submitting form show the login form'''
form= LoginForm()
context={'form': form}
return render_to_response('login.html',context,context_instance= RequestContext(request))
def LogoutRequest(request):
logout(request)
return HttpResponseRedirect('/')
Its HttpResponseRedirect not HttpRequestRedirect.
Change this return HttpRequestRedirect('/profile/') to return HttpResponseRedirect('/profile/')
P.S. Never use hardcoded urls in your code, use Reverse Resolution of URLs

UnBound LocalError in Django?

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':