2015-02-02 11 views
0

아마도 모든 나무 때문에 숲을 볼 수 없지만 매우 이상한 문제가 있습니다.장고 하위 모델이 템플릿에 나타나지 않습니다.

views.py :

from django.shortcuts import render 
from models import Question, QuestionAnswerAlloc, Section 

def home(request): 
    sections = Section.objects.all() 
    for s in sections: 
     questions = Question.objects.filter(section=s) 
     for q in questions: 
      answersalloc = QuestionAnswerAlloc.objects.filter(question=q) 
      q.answers.append(answersalloc) 
     s.questions.append(questions) 

    return render(request, "questionaire/index.html", {'sections': sections}) 

models.py :

from django.db import models 

from portal.models import Customer 


class Section(models.Model): 
    title = models.CharField(max_length=150) 
    weight = models.FloatField() 
    maxscore = models.FloatField() 

    questions = [] 

    def __unicode__(self): 
     return "%s" % (self.title) 


class Question(models.Model): 
    title = models.TextField() 
    section = models.ForeignKey(Section) 
    weight = models.FloatField() 

    answers = [] 

    def __unicode__(self): 
     return self.title 


class Answer(models.Model): 
    title = models.CharField(max_length=150) 
    points = models.IntegerField(default=0, help_text="This has to be a value between 0 and 5") 
    is_weighted = models.BooleanField(default=True, help_text="If this answer does not apply (N/a) it is not weighted!") 

    def __unicode__(self): 
     return self.title 


class QuestionAnswerAlloc(models.Model): 
    question = models.ForeignKey(Question) 
    answer = models.ForeignKey(Answer) 

    def __unicode__(self): 
     return "Possible Answer" 


class Report(models.Model): 
    STATUS_STARTED = "started" 
    STATUS_FIN = "finished" 
    STATUS_INPROG = "inprogress" 
    STATUS_ABORT = "aborted" 

    date = models.DateField(auto_now_add=True, blank=True) 
    title = models.CharField(max_length=150) 
    started_time = models.DateTimeField() 
    end_time = models.DateTimeField() 
    status = models.CharField(max_length=150, default=STATUS_STARTED) 
    guid = models.CharField(max_length=150, unique=True) 

    def __unicode__(self): 
     return self.title 


class ReportAnswer(models.Model): 
    title = models.CharField(max_length=150) 

    orignal_answer = models.ForeignKey(Answer) 
    question = models.ForeignKey(Question) 
    section = models.ForeignKey(Section) 
    report = models.ForeignKey(Report) 

    points = models.FloatField() 
    weight = models.FloatField() 
    is_weighted = models.BooleanField(default=True) 

    customer = models.ForeignKey(Customer, blank=True, null=True) 

    def __unicode__(self): 
     return self.title 

그리고 내 템플릿 :

{% for s in sections %} 
      <div class="row"> 
       <div class="col-sm-12"> 
        <div class="FormStepInfo"> 
         <p class="QuestionaireSectionTitle">{{s.title}}</p> 
         <p class="QuestionaireSectionDesc"></p> 
        </div> 
       </div> 
      </div> 

       {% for q in s.questions %} 
       <div class="row"> 
        <hr/> 
        <div class="col-sm-2 quest-num">{{forloop.counter }}</div> 
        <div class="col-sm-10 quest-title"> 
         <label> 
          {{q.title}} 
         </label> 
         <br/> 

         <div class="CheckboxQuestion"> 
          {% for a in q.answers %} 
          <label for=""><input type="radio" name="Q3" value="{{a.points}}" id="q3a1">{{a.title}}</label> 
          {% endfor %} 
         </div> 
        </div> 
       </div> 
       {% endfor %} 
      {% endfor %} 

불행하게도, 질문의 제목이 표시되지 않습니다, 아니 답변. sys.stderr에 출력하면이 섹션에 질문이 있음을 알 수 있습니다. 내가 놓친 게 있니? 나는 "파이썬 manage.py runserver"를 약 10 번 사용하고 캐시를 삭제하면서 "웹 서버"를 다시 시작했습니다.

+0

어쩌면 내가 잘못,하지만 대신'당신's.questions.extend (질문)를 사용한다고 생각 's.questions.append (questions) '의 – trnsnt

답변

0

Python의 클래스 정의에 대한 오해가 상당히 있습니다. 일반적으로 클래스 수준에서 속성을 정의하면 클래스의 모든 구성원이 속성을 공유합니다. Django 필드는 값이 클래스가 아닌 인스턴스 단위인지 확인하기 위해 특별한 마법을 사용하지만 questionsanswers 목록은 그렇게하지 않습니다. 따라서 코드를 작동시킬 수 있다고하더라도 모든 대답은 모든 질문과 관련이 있습니다.

운 좋게도이 작업을 수행 할 필요가 없습니다. Django는 필요한 것을 정확하게 제공하는 역방향 접근자를 제공합니다.

def home(request): 
    sections = Section.objects.all() 
    return render(request, "questionaire/index.html", {'sections': sections}) 

하고 뷰가된다 : 그래서보기는 그냥 간단하게 할 수

{% for s in sections %} 
    ... 
    {% for q in s.question_set.all %} 
     ... 
     {% for a in q.questionansweralloc_set.all %} 

     ...etc 
+0

좋아, 그 말도 안되게 쉬웠다. 고마워요! – Richard

관련 문제