Django didn't return an HttpResponse object问题

急救,大老板们指点~
运行的时候直接报错,The view bookstore.views.update_book didn't return an HttpResponse object. It returned None instead.
**尝试按照网上的方案去修改缩进量,但是无效。__**

```python
def update_book(request, book_id):
    try:
        book = Book.objects.get(id=book_id, is_active=True)
    except Exception as e:
        print('update book error is %s' % e)
        return HttpResponse('book is not existed')
    if request == 'GET':
        return render(request, 'bookstore/update_book.html', locals())
    elif request == 'POST':
        market_price = request.POST['market_price']
        price = request.POST['price']
        book.price = price
        book.market_price = market_price
        book.save()
        return HttpResponseRedirect('/bookstore/all_book')



template 里面的html 如下:

```html
html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>update booktitle>
head>
<body>

<form action="/bookstore/update_book/{{ book.id }}" method="POST">
    <p>
        title <input type="text" value="{{ book.title }}" disabled="disabled">
    p>
    <P>
        pub <input type="text" value="{{ book.pub }}" disabled="disabled" >
    P>
    <p>
        price <input type="text" name="price" value="{{ book.price }}">
    p>
    <p>
        market_price <input type="text" name="market_price" value="{{ book.market_price }}" >
    p>
    <p>
        <input type="submit" value="renew">
    p>

form>

body>
html>


运行结果及详细报错内容

The view bookstore.views.update_book didn't return an HttpResponse object. It returned None instead.
Request Method: GET
Request URL: http://127.0.0.1:8000/bookstore/update_book/1
Django Version: 4.1.7
Exception Type: ValueError
Exception Value:
The view bookstore.views.update_book didn't return an HttpResponse object. It returned None instead.
Exception Location: D:\JNU\mysite\venv\Lib\site-packages\django\core\handlers\base.py, line 332, in check_response
Raised during: bookstore.views.update_book
Python Executable: D:\JNU\mysite\venv\Scripts\python.exe
Python Version: 3.11.2

参考GPT和自己的思路:根据你提供的代码,可以看出在函数中有一个代码块缺少返回HttpResponse的语句,导致视图在某些情况下没有返回任何响应。具体来说,update_book函数中的第一个if request == 'GET'条件块中没有将HttpResponse对象返回,所以当请求为GET时会返回None。

要修复这个问题,只需在该条件块中添加一个HttpResponse对象返回即可。下面是修改后的代码示例:

def update_book(request, book_id):
    try:
        book = Book.objects.get(id=book_id, is_active=True)
    except Exception as e:
        print('update book error is %s' % e)
        return HttpResponse('book is not existed')
    
    if request.method == 'GET':
        return render(request, 'bookstore/update_book.html', locals())
    elif request.method == 'POST':
        market_price = request.POST['market_price']
        price = request.POST['price']
        book.price = price
        book.market_price = market_price
        book.save()
        return HttpResponseRedirect('/bookstore/all_book')

注意,我还在第一个条件块中修正了if request == 'GET'if request.method == 'GET' ,因为你需要比较请求的方法类型而不是它的值。

希望这可以帮助您解决问题。