在赋值之前引用的Django错误局部变量'item_id'

时间:2016-09-19 13:24:47

标签: django

我每次都遇到这个错误,我不知道如何解决这个问题。我正在使用jquery发送项目ID来连接会话对象。

我的观点:

def chatpage(request):
if request.method == 'POST':
    item_id = int(request.POST['item_id'])

    return JsonResponse({'status': 200})
    message_form = MessageForm(data=request.POST)

    if message_form.is_valid():
        new_message = message_form.save(commit=False)
        new_message.conversation_id = item_id
        new_message.agreement_delivery_time = 12
        new_message.save()
else:
    message_form = MessageForm()

conversation = Conversation.objects.get(id=item_id)
messages = conversation.message_set.all()

return render(request, 'templates/Chatapp/chat.html',
              {'message_form': message_form,
               'conversation': conversation,
               'messages': messages})

1 个答案:

答案 0 :(得分:0)

请尝试以下代码,如果您正在寻找,请告诉我们:

def chatpage(request):
    if request.method == 'POST':
        item_id = int(request.POST['item_id'])
        message_form = MessageForm(data=request.POST)
        if message_form.is_valid():
            new_message = message_form.save(commit=False)
            new_message.conversation_id = item_id
            new_message.agreement_delivery_time = 12
            new_message.save()
        conversation = Conversation.objects.get(id=item_id)
        messages = conversation.message_set.all()
    else:
        message_form = MessageForm() 
    return render(request, 'templates/Chatapp/chat.html', locals())

您可以通过模板中的名称访问每个变量。