Django:在模板中访问OneToOneField

时间:2015-10-19 13:04:04

标签: python django templates

您好我必须关注Models.py

class Question(models.Model):
    user = models.ForeignKey(User)
    article = models.ForeignKey(Article)
    number = models.CharField("문제번호", max_length=10, null=True, blank=True)
    q_type = models.CharField("문제유형", max_length=15)
    question = models.TextField("문제내용")
    answer = models.TextField("답안", null=True, blank=True)
    reference = models.TextField("참고사항", null=True, blank=True)

    def __str__(self):
        return "%s번: %s" % (self.number, self.question)

class Professor(models.Model):
    question = models.OneToOneField(Question, null=True, blank=True, related_name="related_professor")
    articles = models.ManyToManyField(Article, null=True, blank=True)
    name = models.CharField("교수이름", max_length=20)

    def __str__(self):
        return "%s" % (self.name,)

Views.py:

def read_q_table(request, board_id, article_id):
    article = get_object_or_404(Article, id=article_id)

    context = {
        "boards" : Board.objects.all(),
        "board_id" : board_id,
        "questions" : Question.objects.all().order_by("number"),
        "article" : article,
        "professor" : Professor.objects.all()
    }
    return render(request, "q_table.html", context)

模板:

{% if questions %}
    {% for question in questions %}
    <div class="list-group-item">
        <div class="row text-center">
            <div class="col-xs-2 col-md-2">{{ question.related_professor.name }}</div>
        </div>
    </div>
    {% endfor %}
{% else %}

我想要的是访问模板中的教授姓名字段。我已经在上下文中列出了&#34;问题&#34;类对象到模板,我想以某种方式使用OneToOneField属性来访问模板中的相关教授名称。

根据Accessing Django OneToOneField in templates?,{{问题。 related_professor.name}}应该有效,但它没有。有人可以帮忙吗? 感谢。

或者,这可能是首先保存教授数据的问题。以下代码采用表单输入并提交它们以保存它们。

Professor.objects.get(name=professor).question = question_instance
Professor.objects.get(name=professor).save()

def submit_question中的这两行可能会引起人们的注意,但我不确定。在这里,我试图获取相关的教授实例并更新其问题字段(与Question类相关的OneToOneField)。

def submit_question(request, board_id, article_id):
    article = get_object_or_404(Article, id= article_id)

    try:
        professor = request.POST["professor"].strip()
        q_type = request.POST["q_type"].strip()
        question = request.POST["question"].strip()
        number = request.POST["number"].strip()
        reference = request.POST["reference"].strip()
        if request.POST['q_type']== "주관식":
            answer = request.POST['d_answer'].strip()
        else:
            answer = request.POST['m_answer'].strip()
    except KeyError:
        request.session["error"] = "올바른 요청이 아닙니다."
        return redirect("read_article", board_id, article_id)

    if professor and q_type and question:
        question_instance = article.question_set.create(q_type = q_type, question = question, user_id = request.user.id)
        Professor.objects.get(name=professor).question = question_instance
        Professor.objects.get(name=professor).save()

    if number:
        question_instance.number = number

    if answer:
        question_instance.answer = answer

    if reference:
        question_instance.reference = reference

        question_instance.save()

    else:  
        request.session["error"] = "출제교수, 문제유형 및 문제는 필수 입력 항목입니다."
        return redirect("read_article", board_id, article_id)
    return redirect("read_q_table", board_id, article_id) 

1 个答案:

答案 0 :(得分:2)

这两行是可疑的:

Professor.objects.get(name=professor).question = question_instance
Professor.objects.get(name=professor).save()

第二行将从数据库再次获取教授,并且在保存时不会再附加您的问题实例。试试这个:

prof = Professor.objects.get(name=professor)
prof.question = question_instance
prof.save()