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

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

Related

Django error with views for form display and save

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

Why my form in Django is not valid ? Never do the condition

I'm trying to save the default data of my form and model with a simple function in Django but when I use the condition of is_valid() never enter to the condition. What can I do ?
This is for views.py
def entreno1B(request):
if request.method == 'POST':
form=Entreno(request.POST)
if form.is_valid():
print("is valid")
form.save()
return render(request, 'training/entrenosB1.html')
my model is
class Entrenos(models.Model):
tiempo1D1 = models.FloatField(max_length=1000,default=0.0)
tiempo2D1 = models.FloatField(max_lenght=1000,default=0.0)
and my form is
class Entreno(forms.ModelForm):
class Meta:
model = Entrenos
fields = ('tiempo1D1','tiempo2D1',)
Please Help. I don't know what is my error. Thank you
Also, when I modify my views like this:
def entreno1B(request):
if request.method == 'POST':
form=Entreno(request.POST)
form.save()
if form.is_valid():
print("is valid")
form.save()
return render(request, 'training/entrenosB1.html')
I got the error that my object has no attibute 'cleaned_data'
I modify my function in views.py, and works. I do this:
def entreno1B(request):
if request.method == 'POST':
form=Entreno({'tiempo1D1':DATA, 'tiempo2D1':Data2})
if form.is_valid():
print("is valid")
form.save()
return render(request, 'training/entrenosB1.html')

Saved model is None

So i have a model that i'm trying to save using a form which submits successfully, but in the Admin the object value None. I know the problem is in the views but i can't figure it out. Here's my code:
Views.py
def profilecreate(request):
if request.method == 'GET':
form = ProfileForm()
else:
form = ProfileForm(request.POST)
if form.is_valid():
description = form.cleaned_data['description']
caption= form.cleaned_data['caption']
photo = form.cleaned_data['photo']
profile = Profile.objects.create(description=description, caption=caption, photo=photo)
return HttpResponseRedirect(reverse('profile-id', kwargs={'profile_id': profile.id}))
return render(request, 'profile_form.html', {'form': form})
Someone please assist
Second view attempt
def profilecreate(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ProfileForm(request.POST)
# check whether it's valid:
if form.is_valid():
photo = form.cleaned_data['photo']
description = form.cleaned_data['description']
caption = form.cleaned_data['caption']
form.save(commit=True)
return HttpResponseRedirect('/')
# if a GET (or any other method) we'll create a blank form
else:
form = ProfileForm()
return render(request, 'profile_form.html', {'form': form})

Setting value of a form field in Django

I'm attempting to modify a field after the user has submitted the form. I've found several pieces of code online, but none seem to work. Below is my attempt in views.py. Any guidance would be greatly appreciated.
def newlisting(request):
if request.method == "POST":
form = ListingsForm(request.POST)
if form.is_valid():
form.cleaned_data['condition'] = 1 #form.condition = 1 also fails
form.save()
return redirect('/listings/')
else:
form = ListingsForm()
return render(request, 'newlisting/newlisting.html', {'form':form})
you can do like:
def newlisting(request):
if request.method == "POST":
form = ListingsForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.condition = 1
obj.save()
return redirect('/listings/')
else:
form = ListingsForm()
return render(request, 'newlisting/newlisting.html', {'form':form})

How to clear form fields after a submit in Django

I've this:
def profile(request, username):
if request.method == 'POST':
if request.user.is_authenticated():
new_message = Message(author = request.user)
form = MessagesForm(request.POST, instance = new_message)
else:
form = MessagesForm(request.POST)
if form.is_valid():
form.save()
else:
to_user = User.objects.get(username = username)
form = MessagesForm(initial = {'user': to_user.pk})
return render(request, "profile.html", {
'username': username,
'form': form,
'messages': messages,
})
This form submit a message and return the same page. My problem is that after the submit I see again my field filled with my information. How to clear it after the submit?
After saving form instead of showing post dict assign the empty form
form = EmployeeForm()
if request.method == "POST":
pDict = request.POST.copy()
form = EmployeeForm(pDict) #if not valid shows error with previous post values in corresponding field
if form.is_valid():
form.save()
form = EmployeeForm() # show empty form no need to give HttpResponseRedirect()
It's standard to redirect after form submission to prevent duplicates.
Just return a redirect to your form on success.
if form.is_valid():
form.save()
return http.HttpResponseRedirect('')
after save() you can return 'form' key with MessagesForm(request.GET) value.
return render(request, "profile.html", {
'username': username,
'form': MessagesForm(request.GET),
'messages': messages,
})
Usually you can initialize the same empty form after you have saved datas:
if request.method == "POST":
rf = RegistrationForm(request.POST)
if rf.is_valid():
print 'Saving datas..'
#logic to save datas
rf = PreRegistrationForm()
return render_to_response('registration/confirmation_required.html', {'settings': settings}, context_instance=RequestContext(request))
Try using HttpResponseRedirect('/') instead of HttpResponseRedirect('') in #Karthikkumar's answer, especially if your home view is an empty path, for instance you have in your urls.py file:
urlpatterns = [path('',views.home_view),]
I had similar issues as those discussed above where HttpResponseRedirect('') directed me to a blank page. Let me know if adding the slash works for you!
You can use this:
Sometimes you can use this idea take attrs={ "autocomplete":"off"} for each inputs.
You can redirect back to the initial post
post_url = request.build_absolute_uri(post.get_absolute_url())
return HttpResponseRedirect(post_url)
please note that 'post' is an instance of the model created
I am hoping you have already defined a logic for GET methods. In the case that you have, all you can do is simply add return request.META['HTTP_REFERER'] at the end.
See what I mean:
def profile(request, username):
if request.method == 'POST':
if request.user.is_authenticated():
new_message = Message(author = request.user)
form = MessagesForm(request.POST, instance = new_message)
else:
form = MessagesForm(request.POST)
if form.is_valid():
form.save()
else:
to_user = User.objects.get(username = username)
form = MessagesForm(initial = {'user': to_user.pk})
return HttpResponseRedirect(request.META['HTTP_REFERER'])
This should work, I just tested it.
**Maybe I am late but for Django 4.x developers can use: **
from .forms import TodoForm
from django.contrib import messages
from django.http import HttpResponseRedirect
def mytodos(request):
form = TodoForm()
if request.method =='POST':
form=TodoForm(request.POST)
if form.is_valid:
form.save()
messages.success(request,'Task saved successfully')
return HttpResponseRedirect('/todo/')
mycontext={'form':form}
return render(request, 'todo/todo.html',mycontext)
in my urls.py: , i have set path('todo/',views.mytodo, name='todolist')
As you can see, after saving form, mycode will redirect to /todo/ which is automatically refreshed after every submit and a fresh form comes again everytime. If you are a good django dev, you will understand what I did. Make sure to reply if you have any queries .Thanks :)
When we reload the page (F5 or ctrl+shift+R), it submits the previously sent data. so instead of refreshing, we will directly hit the url using return HttpResponseRedirect('/posts/')
This way it will show the page with empty form (now even if you refresh it will only show data, won't submit it previous data again)
from django.shortcuts import render, HttpResponseRedirect
from django.views import View
from .models import Post
from .forms import PostForm
class PostListView(View):
def post(self, request, *args, **kwargs):
posts = Post.objects.filter(author=request.user).order_by('-created_on')
form = PostForm(request.POST)
if form.is_valid():
new_post = form.save(commit=False)
new_post.author = request.user
new_post.save()
return HttpResponseRedirect('/posts/')
context = {
'post_list': posts,
'form': form
}
return render(request, 'social/post_list.html', context)