Can't get key to display in Django template

回眸只為那壹抹淺笑 提交于 2019-12-24 23:24:29

问题


I have been trying for about a day and a half to get the ID of a related field in a model to display in my template. Nothing fancy, I just want the ID.

Here is the model in question:

class CompositeLesson(models.Model):
    lesson = models.ForeignKey(Lesson)
    student = models.ForeignKey(Student)
    actualDate = models.DateTimeField()

Assume I have a list, lessonsList, of CompositeLesson and am able to successfully iterate through the list. Other fields (i.e. actualDate) display correctly.

Snippet of template code:

{% for lesson in lessonsList %}
<tr{% if forloop.counter|divisibleby:"2" %} class="shaded_row"{% endif %}>
    <td>{{ lesson.actualDate }}</td>
    <td class="table_button">
    {% if not lesson.isCancelled %}
        <div class="table_button_div" id="cancel_{{ lesson__lesson__id }}"><a href="#">Cancel Lesson</a></div>
    {% else %}
        <div class="cancelled_lesson"></div>
    {% endif %}

The problem is I can't get the ID of the Lesson object that is in the list. I've tried:

lesson.lesson
lesson.lesson.id
lesson.lesson__id
lesson__lesson__id
lesson.lesson.get_id

...and none of them work.

Thanks in advance!

Edit: here is my view that builds the lesson, per request:

def all_student_lessons(request, id):
    # This should list all lessons up to today plus the next four, and call out any cancelled or unpaid lessons
    # User should have the option to mark lessons as paid or cancel them
    s = Student.objects.get(pk = id)
    if s.teacher != request.user:
        return HttpResponseForbidden()

    less = Lesson.objects.filter(student = id)
    lessonsList = []
    for le in less:
        if le.frequency == 0:
            # lesson occurs only once
            x = CompositeLesson()
            x.lessonID = le.id
            x.studentID = id
            x.actualDate = datetime.combine(le.startDate, le.lessonTime)
            x.isCancelled = False
            try:
                c = CancelledLesson.objects.get(lesson = le.id, cancelledLessonDate = le.startDate)
                x.canLesson = c.id
                x.isCancelled = True
            except:
                x.canLesson = None
            try:
                p = PaidLesson.objects.get(lesson = le.id, actualDate = le.startDate)
                x.payLesson = p.id
            except:
                x.payLesson = None
            lessonsList.append(x)
        else:
            sd = next_date(le.startDate, le.frequency, le.startDate)
            while sd <= date.today():
                x = CompositeLesson()
                x.lessonID = le.id
                x.studentID = id
                x.actualDate = datetime.combine(sd, le.lessonTime)
                x.isCancelled = False
                try:
                    c = CancelledLesson.objects.get(lesson = le.id, cancelledLessonDate = le.startDate)
                    x.canLesson = c.id
                    x.isCancelled = True
                except:
                    x.canLesson = None
                try:
                    p = PaidLesson.objects.get(lesson = le.id, actualDate = le.startDate)
                    x.payLesson = p.id
                except:
                    x.payLesson = None
                lessonsList.append(x)
                sd += timedelta(le.frequency)
    lessonsList.sort(key = lambda x: x.actualDate)
    return render_to_response('manage_lessons.html', {'lessonsList': lessonsList,
                                                    's': s})

回答1:


In your view, you're never assigning x.lesson . It's logical then, that lesson.lesson is undefined.

You should replace x.lessonID = le.id for x.lesson = le

If that doesn't work, also try an x.save() before a lessonsList.append(x).

On a sidenote, your model doesn't seem to be too well defined, because you're adding new attributes to it that aren't defined in the model. Also, you may consider creating and storing the CompositeLesson objects before the view in which they are displayed. You may want to create or modify these objects whenever some other important event occurs, such as the lessons being scheduled, payed or cancelled.




回答2:


And, it appears I was right. The problem is that you're not dealing with a queryset, here, but rather a custom data structure that you've set up. Simply instantiating a CompositeLesson doesn't save it to the database. So what you have is a list of instantiated CompositeLesson models with no correlation to actual database records, but which depend on the database to ascertain values like your lesson FK.

Long and short, lesson.lesson is undefined in your template context, so of course anything like lesson.lesson.id is also undefined. I'm not really sure honestly how to correct this problem, because you code is an unmitigated mess. My suggestion would to be to go back to the drawing board, and if you need help figuring out the best way to accomplish what you're trying to achieve, open a new question. I don't believe what you have is workable, and even if you get it working, it's such a bastardization of the Django ORM that you're at the best going to make whichever poor developer inherits your codebase in the future want to murder you with a rusted rake.



来源:https://stackoverflow.com/questions/10935801/cant-get-key-to-display-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!