简体   繁体   中英

Django: Accessing OneToOneField in template

Hi I have to following 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)

Template:

{% 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 %}

What I want is to access professor name field in template. I have passed in context the list of "question" class objects to template, and I would like to use OneToOneField attribute somehow to access related professor name in template.

According to Accessing Django OneToOneField in templates? , {{ question. related_professor.name }} should work, but it doesn't. Can anyone help? Thanks.

Or, it could be a problem with saving the professor data in the first place. The following code takes form input and submit them to save them.

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

These two lines in def submit_question may raise an eyebrow but I am not sure. Here I am trying to get the related professor instance and update its question field(a OneToOneField that relates to Question class).

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) 

These two lines are suspect:

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

The second line will get the Professor from the database again , and it won't have your question instance attached anymore when you save it. Try this instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM