Home > Enterprise >  ValueError at /form The view authentication.views.my_form didn't return an HttpResponse object.
ValueError at /form The view authentication.views.my_form didn't return an HttpResponse object.

Time:11-04

I am trying to create a form but facing issues, any kind of help will be appreciated. Thanks in advance. Below is my views.py

from django.contrib.auth import authenticate, login, logout
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import send_mail, EmailMessage
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib import messages
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from . tokens import generate_token
from Database import settings
from django.shortcuts import render
from .models import Inventory_Details
from .forms import MyForm

def my_form(request):
    if request.method == "POST":
        form = my_form(request.POST)
        if form.is_valid():
            form.save()
        else:
            form = my_form()
            return render(request, "authentication/Inventory_details.html", {'form': form})

detail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Inventory_details</title>
</head>
<body>
<div >
    <form method="POST">
      <fieldset>
        <legend>Form</legend>
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" >Submit</button>
      </fieldset>
    </form>
</div>
</body>
</html>

Below is the error message:

ValueError at /form

The view authentication.views.my_form didn't return an HttpResponse object. It returned None instead.

Thanks

CodePudding user response:

I think you did mistake here. else part should be part of first if statement.

instead:

def my_form(request):
    if request.method == "POST":
        form = my_form(request.POST) #You mispelled my_form. You imported from .forms import MyForm. write MyForm here instead of my_form
        if form.is_valid():
            form.save()
        else: #You did mistake here that's why you got that error
            form = my_form()
            return render(request, "authentication/Inventory_details.html", {'form': form})

change this:

def my_form(request):
    if request.method == "POST":
        form = MyForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/home/') #Add your path here
    else:
        form = MyForm()
    return render(request, "authentication/Inventory_details.html", {'form': form})
  • Related