djnago中的“赋值之前引用了局部变量'response'”错误

时间:2019-04-20 12:14:37

标签: python django django-models django-rest-framework

##创建视图'add_car'方法时,我试图为'response'变量赋值,但显示错误。如果我输入'response = None',则输出为None

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

import json
from .models import Car

def index(request):
    response=json.dumps([{}])
    return HttpResponse(response,content_type='text/json')
def get_car(request,car_name):
    if request.method == 'GET':
        try:
            car=Car.objects.get(name=car_name)
            response=json.dumps([{'Car':car.name,'Top speed':car.top_speed}])
        except:
            response=json.dumps([{'Error':'No car with that name'}])
    return HttpResponse(response,content_type='text/json')
@csrf_exempt
def add_car(request):
    #response=None
    if request.method =='POST':
        payload=json.loads(request.body)
        car_name=payload['car_name']
        top_speed=payload['top_speed']
        car=Car(name=car_name,top_speed=top_speed)
        try:
            car.save()
            response=json.dumps([{'Success':'Car added succesfully'}])
        except:
            response=json.dumps([{'Error':'Car could not ne added'}])
    return HttpResponse(response,content_type='text/json')

1 个答案:

答案 0 :(得分:0)

可能您不使用@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinTable(...) @MapKeyJoinColumn(name = "relationship_id") private Map<Relationship, MyEntity> relationships = new HashMap<>(); 方法调用此视图。

POST尚未执行,因此if request.method =='POST':找不到响应变量。