将代码从Django移植到Django 2.0时配置不当

2024-04-19 02:09:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试做一些基于django1.8的书中描述的项目。此部分应为学生报名参加某些课程:

CBV:

class CourseDetailView(DetailView):
    model = Course
    template_name = 'courses/manage/course/detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['enroll_form'] = CourseEnrollForm(initial={'course': self.object})

形式:

class CourseEnrollForm(forms.Form):
    course = forms.ModelChoiceField(queryset=Course.objects.all(), widget=forms.HiddenInput)

带有“注册”按钮的HTML(detail.HTML)

{% if request.user.is_authenticated %}
    <form action="{% url "students:student_enroll_course" %}" method="post">
           {{ enroll_form }}
           {% csrf_token %}
        <input type="submit" class="button" value="Enroll now">
    </form>
{% else %}
     <a href="{% url "students:student_registration" %}" class="button">Register to enroll</a>
{% endif %}

成功注册后的HTML(简称):

{% with subject=course.subject %}
    <h1>{{ object.title }}</h1>
    <div class="module">
       <h2>Overview</h2>
       <p>
         <a href="{% url "elearning:course_list_subject" subject.slug %}">{{ subject.title }}</a>.
         {{ course.modules.count }} modules.
         Instructor: {{ course.owner.get_full_name }}
       </p>
    </div>
{% endwith %}

有了这个,我得到了一个错误NoReverseMatch——接下来我注释掉<a>标记——页面加载了,但是都是空的{{ }} template variables。当我点击Enroll按钮-我得到:

ImproperlyConfigured at /students/enroll-course/
TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'

看起来Course模型实例没有传递到Django模板中。但为什么会这样呢?一本书说这个代码应该有效。Django 2.0中的这些东西有什么变化吗?

P.S.如果我注释掉一个get_context_data方法-页面加载了所有模板变量,但仍然Enroll按钮抛出相同的ImproperlyConfigured错误


Tags: nameformurldatagethtmlcontexttemplate