我是Django的初学者,我有一个问题.... 我创建了一个包含3个模型的应用程序(名称:PQR)(患者/问题/回复) 我想在顶部看到患者姓名的视图,在此之下,所有可用的问题以及问题旁边的答案(某些患者可能有空回复/无回复)。 我知道如何显示患者的答案,但我想显示每个问题,如果有的话,我想提供答复,但我不知道如何在我看来写这个?
这是我的模特:
Class Patient(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
def listReply(self):
replies = Reply.objects.filter(patient= self.id)
return replies
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question_text
class Reply(models.Model):
question = models.ForeignKey(Question)
patient = models.ForeignKey(Patient)
reply_text = models.CharField(max_length=200)
def __unicode__(self):
return str(self.reply_text)
这是我的观点:
from django.shortcuts import render, get_object_or_404
from django.template import RequestContext
from .models import Patient, Question, Reply
def list(request):
list_patient = Patient.objects.order_by('name') context = RequestContext(request, {'list_patient':list_patient,'welcome': 'Welcome on my page Django !',
})
return render(request, 'PQR/list.html', context)
def detail(request, patient_id):
patient = get_object_or_404(Patient, pk=patient_id)
list_question = Question.objects.all()
Replies4MyPatient = Reply.objects.filter(patient=patient_id)
return render(request, 'PQR/detail.html', locals())
这是我的网址:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.list, name ='list_patient'),
url(r'^(?P<patient_id>[0-9]+)/patient/$', views.detail, name ='detail_patient'),
这是我的模板:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'Forum/style.css' %}" />
<div>
<h1>Patient details : {{ patient }}</h1>
</div>
<fieldset>
{% csrf_token %}
{% for reply in Replies4MyPatient %}
</br><abcd>{{ reply.question }}</abcd></br>
</br>
<li>{{ reply }}</li>
{% endfor %}
</fieldset></br>
<a href="{% url 'list_patient' %}"/> <input type="button" value="Look Back"/>
感谢您的帮助!
答案 0 :(得分:0)
函数render
构建html以返回模板和上下文。在您的模板PQR/detail.html
中,您使用{{ patient }}
和Replies4MyPatient
。您需要使用这些值构建上下文并将其传递给render
def detail(request, patient_id):
patient = get_object_or_404(Patient, pk=patient_id)
list_question = Question.objects.all()
Replies4MyPatient = Reply.objects.filter(patient=patient_id)
context = {'patient' : patient, 'Replies4MyPatient' : Replies4MyPatient}
return render(request, 'PQR/detail.html', context=context)