0

我想访问属于特定课程的内容列表。我应该如何写我的观点和网址来访问它。我已经为课程列表编写了视图和网址,但有些无法访问每门课程中的内容

from django.contrib.auth.models import User
from django.db import models
import datetime 
from django.utils import timezone
from django.template.defaultfilters import slugify



class PostManager(models.Manager):
    def live(self):
        return self.model.objects.filter(published=True)



class Course(models.Model):
    course_name = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, blank=True, default='')
    pub_date = models.DateTimeField('date published')
    author = models.ForeignKey(User, related_name="courses")
    published_course = models.BooleanField(default=True)
    objects = PostManager()

    class Meta:
        ordering = ["-pub_date", "course_name"]

    def __unicode__(self):
        return self.course_name

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date < now

    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently ?'   

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.course_name)
        super(Course, self).save(*args, **kwargs)

    @models.permalink   
    def get_absolute_url(self):
        return ("course:detail", (), {"slug": self.slug})


class Content(models.Model):
    course = models.ForeignKey(Course)
    topic_name = models.CharField(max_length=200)
    slug_topic_name = models.SlugField(max_length=200, blank=True, default='')
    desc = models.TextField()
    published = models.BooleanField(default=True)
    objects = PostManager()

    def __unicode__(self):
        return self.topic_name

    def save(self, *args, **kwargs):
        if not self.slug_topic_name:
            self.slug_topic_name = slugify(self.topic_name)
        super(Content, self).save(*args, **kwargs)

    @models.permalink   
    def get_absolute_url(self):
        return ("content:detail", (), {"slug_topic_name": self.slug_topic_name})

我的课程/views.py

from django.views.generic import ListView, DetailView

from .models import Course, Content


class CourseListView(ListView):
    model = Course

    def get_queryset(self):
        queryset = super(CourseListView, self).get_queryset()
        return queryset.filter(published_course=True)

class CourseContentListView(ListView):

    context_object_name = 'content_list'
    queryset = Content.objects.filter(course__course_name='HTML5')
    template_name = 'content/content_list.html'

我的课程/urls.py

from django.conf.urls import patterns, url

from . import views

urlpatterns = patterns('',
    url(r"^$", views.CourseListView.as_view(), name="list" ),
    url(r"^(?P<course_name>[\w-]+)/$", views.CourseContentListView.as_view(), name="list"),
)

项目/urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin


from . import views

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'kodeworms.views.home', name='home'),
    # url(r'^kodeworms/', include('kodeworms.foo.urls')),
    url(r"^$", views.HomepageView.as_view(), name="home"),
    url(r"^course/", include("course.urls", namespace="course")),
    url(r"^course/content", include("course.urls", namespace="content")),   

    url(r'^admin/', include(admin.site.urls)),
)

项目\课程\模板\课程\course_list.html

{% extends "_layouts/base.html" %}
{% load url from future %}

{% block page_title %}Course List | {% endblock %}

{% block page_content %}
<h2>Course Grid</h2>

<ul>
    {% for course in course_list %}
    <li><a href="{% url 'content:list' %}">{{ course.course_name }}</a></li>
    {% empty %}
    <li>Sorry, no courses yet. Check back soon! </li>
    {% endfor %}
    <p><a href="{% url 'home' %}">&larr; Home</a></p>
</ul>
{% endblock %}

项目\课程\模板\内容\content_list.html

{% extends "_layouts/base.html" %}

{% block page_title %}{{ course.course_name }} | {% endblock %}


{% block page_content %}
<h2>{{ course.course_name }}</h2>
{{ course.content|linebreaks }}

<ul>
    {% for content in object_list %}
    <li>{{ content.topic_name }}</li>
    {% empty %}
    <li>Sorry, no content yet. Check back soon! </li>
    {% endfor %}
</ul>

<p><a href="{% url 'course:list' %}">&larr; Course List</a></p>
{% endblock %}

在上面的代码中,我已经硬编码了课程名称的内容。我想为任何任意课程动态获取它。我的 pk=1 也给出错误, pk=8/9/10 有值。有人可以帮忙吗

4

3 回答 3

0

好的,这是我的第一个 Web 项目,也是投票应用程序之后的第一个 Django 项目。所以这个解决方案。适合那些像我这样的菜鸟/初学者进入编程/网络开发世界的人。

我的 pk 是从 pk=8 开始的,所以我不知道如何使用它访问内容列表。但是随后通过阅读一些 Django 文档并从此链接中回答,我能够找出问题并解决问题。无论如何这里是修改后的代码

views.py -> 早些时候课程被硬编码以访问内容列表,我还尝试使用主键动态访问内容(我没有成功)。所以现在我尝试用 slug 访问它并成功了。

class CourseContentListView(ListView):

    template_name = 'course/content_list.html'

    def get_queryset(self):
        self.course = get_object_or_404(Course, slug=self.kwargs['slug'])
        return Content.objects.filter(course=self.course, published=True)

我还从官方文档中阅读了有关 Django 模板的更多信息,并找出了命名和访问 url 的正确方法,并对 course_list.html 进行了更改以访问内容列表

course_list.html

<ul>
    {% for course in course_list %}
    <li><a href="{% url 'course:content_list' course.slug %}">{{ course.course_name }}</a></li>
    {% empty %}
    <li>Sorry, no courses yet. Check back soon! </li>
    {% endfor %}
    <p><a href="{% url 'home' %}">&larr; Home</a></p>

</ul>

更改 urls.py 以正确指向适当的 url

我的网址.py

urlpatterns = patterns('',
    url(r"^$", views.CourseListView.as_view(), name="list" ),
    url(r"^(?P<slug>[\w-]+)/$", views.CourseContentListView.as_view(), name="content_list"),
)

我还在学习,所以上面的代码中可能会有错误,甚至是更好/优雅的方法。但是话又说回来,这段代码对我有用。

于 2013-07-31T13:03:55.867 回答
0
a = Course.objects.get(pk=1)
# List of contents for this course
course_contents = a.content_set.all()
于 2013-07-29T18:16:19.483 回答
0

您应该将 CourseContentListView 更改为:

class CourseContentListView(ListView):

    model = Content
    context_object_name = 'content_list'
    template_name = 'content/content_list.html'

    def get_queryset(self):
        queryset = super(CourseContentListView, self).get_queryset()
        course_name = self.kwargs.get('course_name')
        course = Course.objects.get(course_name=course_name)
        queryset = queryset.filter(course=course)
        return queryset
于 2013-07-31T13:48:23.693 回答