2017-06-04 49 views
0

我正在爲移動應用程序製作一個簡單的python3 django服務器。 但在views.py中,我在測試時遇到錯誤。Django - 名稱視圖調用模型的對象時出錯

這是功能之一。

from django.shortcuts import render 
from django.http import HttpResponse 
from django.http import JsonResponse 
from bns_info.models import Character, Dungeon, Tactics, Team 
import json 
import hashlib 
import time 

def login(request): 
    if request.method == 'POST': 
     data = request.body.decode("utf-8") 
     receivedData = json.loads(data) 

     receivedName = receivedData['characterName'] 
     character = Character.objects.get(name=receivedName) 
     team = Team.objects.filter(teamNum=character['teamNum']) 
     teamDungeonType = Dungeon.objects.filter(dType=team['dType']) 

     retValue = {character['teamNum']:teamDungeonType['dType']} 
     return JsonResponse(retValue, safe=False) 

    else: 
     return HttpResponse('Request is not POST method.') 

這是我的模型設計。

class Character(models.Model): 
    name = models.TextField(blank=True, null=True) 
    teamNum = models.IntegerField(db_column='teamNum', blank=True, null=True) # Field name made lowercase. 
    id = models.IntegerField(blank=True, primary_key=True) 

    class Meta: 
     db_table = 'Character' 

而我得到了一些錯誤,這是消息。

Internal Server Error: /login/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Dalek_Sec/BnS_Info/Server/appServer/bns_info/views.py", line 18, in login character = Character.objects.filter(name=receivedName) NameError: name 'Character' is not defined [04/Jun/2017 21:11:54] "POST /login/ HTTP/1.1" 500 60733

我認爲這是不夠,我在模型中定義的「性格」,但Django的說是沒有定義的字符。有什麼問題???

+4

下次請不要事後誤差爲圖像。這裏發生的是這個oyu忘記了導入字符模型 – e4c5

+0

我寫了「from(appname).models import *」,但它仍然會說同樣的錯誤 –

+0

那麼如果這是您的導入語句,我並不感到驚訝。 http://stackoverflow.com/help/how-to-ask – e4c5

回答

0

編輯您的看法是這樣,

def login(request): 
    if request.method == 'POST': 
     data = request.body.decode("utf-8") 
     receivedData = json.loads(data) 
     receivedName = receivedData['characterName'] 
     character = Character.objects.get(name=receivedName) 
     team = Team.objects.get(teamNum=character.teamNum) 
     teamDungeonType = Dungeon.objects.get(dType=team.dType) 
     retValue = {character.teamNum : teamDungeonType.dType} 
     return JsonResponse(retValue, safe=False) 
    else: 
     return HttpResponse('Request is not POST method.') 
+0

謝謝。我完全認爲是錯誤的。我必須使用'。'調用對象的屬性,但我用['〜'] .. !!它效果很好,謝謝大家:) –

相關問題