Django自定义类与视图开发遇属性/类型错误,求解决方向
Django自定义类视图报错解决
问题背景
我创建了以下自定义类,尝试在Django视图中输出其内容,但持续遇到各类AttributeError和TypeError,恳请指点解决方向。
原自定义类代码
from pickle import OBJ from urllib.request import HTTPPasswordMgr from django.shortcuts import render from django.http import request class Bloodcancer(): def __init__(self, my_symptoms=None, my_causes=None, my_treatments=None): self.symptoms = my_symptoms self.causes = my_causes self.treatments = my_treatments class AcuteMyeloidLeukemia(Bloodcancer): def my_symptoms(): symptomatology = { tuple({'a': "pale appearance",'b': "weakness or feeling tired", 'c': "shortness of breath", 'd': "easy brusing or bleeding",'e': "petechiae which are flat, pinpoint spots under the skin caused by bleeding", 'f': "loss of weight", 'g': "loss of appetite", 'h': "fever", 'i': "frequent minor infection"} ) } print (symptomatology) def my_causes(self): causes = ['age', 'being male', 'genes', 'environment', 'other bone marrow diseases'] return render(request, 'Healthcare/Conditions/Blood/Causes.html', {{causes}}) def my_treatments(self): treatments = ['induction therapy', 'consolidation therapy', 'chemotherapy', 'allogenic stem cell transplantation', 'central nervous system treatment', 'treatment of older and frail patients with AML', 'Treatment of refractory or relapsed AML', 'Supportive treatment'] return render(request, 'Healthcare/Conditions/Blood/Treatments.html', {{treatments}})
原views.py代码
from django.shortcuts import render from django.http import HttpResponseBadRequest, request from django.urls import path from Healthcare.Conditions.Blood.blood import AcuteMyeloidLeukemia as a def symptoms_view(self): sample_set = a.my_symptoms() x = sample_set['b'].get() return render('Symptoms.html', {xx})
原urls.py代码
from datetime import datetime from django.urls import path from django.contrib import admin from django.contrib.auth.views import LoginView, LogoutView from Healthcare import views urlpatterns = [ path('admin/', admin.site.urls), path('Healthcare/Conditions/Blood/Symptoms/', views.symptoms_view) ]
错误分析与修正方案
1. 类方法基础错误
AcuteMyeloidLeukemia.my_symptoms缺少self参数(实例方法必须包含该参数),且没有返回值,同时错误地用tuple()包裹字典创建了无效的键值结构。- 类方法中不能直接导入
request,render的第一个参数必须是视图传递过来的请求对象。 - 模板上下文传递错误:
{{causes}}是无效语法,需用{'key': value}的标准字典格式。
2. 视图函数错误
- Django视图函数第一个参数必须是
request(请求对象),而非self。 - 调用类的实例方法前,必须先实例化类。
render函数的正确参数顺序是:render(request, 模板路径, 上下文字典),原代码缺少request参数,且{xx}是无效的上下文写法。
3. 冗余导入清理
- 自定义类中
pickle.OBJ、urllib.request.HTTPPasswordMgr属于无用导入,应删除。
修正后的代码
自定义类(blood.py)
from django.shortcuts import render class Bloodcancer(): def __init__(self, my_symptoms=None, my_causes=None, my_treatments=None): self.symptoms = my_symptoms self.causes = my_causes self.treatments = my_treatments class AcuteMyeloidLeukemia(Bloodcancer): def my_symptoms(self): # 直接返回正常字典结构,无需tuple包裹 symptomatology = { "a": "pale appearance", "b": "weakness or feeling tired", "c": "shortness of breath", "d": "easy brusing or bleeding", "e": "petechiae which are flat, pinpoint spots under the skin caused by bleeding", "f": "loss of weight", "g": "loss of appetite", "h": "fever", "i": "frequent minor infection" } return symptomatology def my_causes(self): return ['age', 'being male', 'genes', 'environment', 'other bone marrow diseases'] def my_treatments(self): return ['induction therapy', 'consolidation therapy', 'chemotherapy', 'allogenic stem cell transplantation', 'central nervous system treatment', 'treatment of older and frail patients with AML', 'Treatment of refractory or relapsed AML', 'Supportive treatment']
views.py
from django.shortcuts import render from Healthcare.Conditions.Blood.blood import AcuteMyeloidLeukemia def symptoms_view(request): # 先实例化类 aml_instance = AcuteMyeloidLeukemia() sample_set = aml_instance.my_symptoms() # 直接通过键获取值,若要处理键不存在的情况可改用get() x = sample_set['b'] # 上下文用字典传递,键为模板中要使用的变量名 return render(request, 'Healthcare/Conditions/Blood/Symptoms.html', {'symptom_b': x, 'all_symptoms': sample_set}) # 新增病因、治疗视图(按需使用) def causes_view(request): aml_instance = AcuteMyeloidLeukemia() causes = aml_instance.my_causes() return render(request, 'Healthcare/Conditions/Blood/Causes.html', {'causes': causes}) def treatments_view(request): aml_instance = AcuteMyeloidLeukemia() treatments = aml_instance.my_treatments() return render(request, 'Healthcare/Conditions/Blood/Treatments.html', {'treatments': treatments})
urls.py
from django.urls import path from django.contrib import admin from django.contrib.auth.views import LoginView, LogoutView from Healthcare import views urlpatterns = [ path('admin/', admin.site.urls), path('Healthcare/Conditions/Blood/Symptoms/', views.symptoms_view), # 添加病因、治疗页面的路由 path('Healthcare/Conditions/Blood/Causes/', views.causes_view), path('Healthcare/Conditions/Blood/Treatments/', views.treatments_view), ]
内容的提问来源于stack exchange,提问作者Neil Faulkner
相关产品推荐
相关产品推荐

