ValueError at /create_post/ - django

When I click the Create New Post button, I get this error.
The service.views.create_post view did not return an HttpResponse
object. Instead, it returned None.
views.py
#login_required
#permission_required("service.add_post")
def create_post(req):
form = PostForm()
if req.method == "POST":
form = PostForm(req.POST)
if form.is_valid():
form.save()
title = form.cleaned_data.get("title")
if title != "POST":
messages.error(req, f"Something went wrong")
return redirect('index')
id = form.cleaned_data.get("pk")
messages.success(req, f"Post {title} was created successfully")
return redirect('index')
return render(req, "create_post.html", {"form":form})
Nothing because I don't understand the error

Related

Error: view didn't return an HttpResponse object

The error occurs when I click button which is linked to the mentioned view
here is my view
def change_company(request,pk):
item = get_object_or_404(Companies, pk=pk)
if request.method == "POST":
form = CompaniesForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('display_companies')
else:
form = CompaniesForm(instance=item)
return render(request, 'change_company.html', {'form':form})
error:
The view companies.views.change_company didn't return an HttpResponse object. It returned None instead.
Change your function to:
def change_company(request,pk):
item = get_object_or_404(Companies, pk=pk)
form = CompaniesForm(instance=item)
if request.method == "POST":
form = CompaniesForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('display_companies')
return render(request, 'change_company.html', {'form':form})

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

How to perform more than one operation in django function view

I'm trying to perform 2 operation with in a single function view. But it perform only first operation. Which operation i mentioned first only that operation is executed second operation is not executed. Any other way to solve this problem.
def home_view(request):
if 'username' in request.session:
if 'username' in request.session:
username = request.session['username']
business_objs = AddBusiness.objects.all().values()
return render(request, 'home/index.html', {'business_objs': business_objs})
elif request.method == 'GET':
username = request.session['username']
form = ProfileForm(request.POST)
if form.is_valid():
profile_info = Profile.objects.filter(username=username).values()
for i in profile_info:
profiledict = i
return render(request, 'home/index.html',
{'profile_first_name': profiledict['first_name'],
'profile_last_name': profiledict["last_name"],
'profile_phone_number': profiledict['phone_number'],
'profile_email': profiledict['email'], 'profile_address': profiledict['address'],
'profile_image': profiledict['image']})
return redirect('/home/')
return redirect('/home/')
else:
return redirect('/login/')
I think you can try like this:
def home_view(request):
if 'username' in request.session:
if 'request.method == 'GET':
username = request.session['username']
business_objs = AddBusiness.objects.all().values()
return render(request, 'home/index.html', {'business_objs': business_objs})
elif request.method == 'POST':
username = request.session['username']
form = ProfileForm(request.POST)
if form.is_valid():
profile_info = Profile.objects.filter(username=username).values()
for i in profile_info:
profiledict = i
return render(request, 'home/index.html',
{'profile_first_name': profiledict['first_name'],
'profile_last_name': profiledict["last_name"],
'profile_phone_number': profiledict['phone_number'],
'profile_email': profiledict['email'], 'profile_address': profiledict['address'],
'profile_image': profiledict['image']})
return redirect('/home/')
return redirect('/home/')
else:
return redirect('/login/')
In that way, you will be able to handle both GET and POST request using this function based view. More information can be found in documentation.

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

Is it possible for superuser to create more than one post, and user to be post only one post?

currently, user can create only one post. but as a superuser I want to create more than one. I tried to do it in admin page but it won't work. Is there a way to do this?
#login_required
def add_category(request):
if Category.objects.filter(author=request.user).exists():
return render(request,'main/category_already_exists.html')
if request.method == 'POST':
category = Category(author=request.user)
form = CategoryForm(request.POST, instance=category)
if form.is_valid():
form.save(commit=True)
return redirect('index')
else:
form = CategoryForm()
return render(request, 'main/add_category.html', {'form':form})
#login_required
def add_category(request):
if not request.user.is_superuser and Category.objects.filter(author=request.user).exists():
return render(request,'main/category_already_exists.html')
if request.method == 'POST':
category = Category(author=request.user)
form = CategoryForm(request.POST, instance=category)
if form.is_valid():
form.save(commit=True)
return redirect('index')
else:
form = CategoryForm()
return render(request, 'main/add_category.html', {'form':form})