在Django中为多对多字段定义视图和URL

时间:2014-03-08 16:02:56

标签: python django many-to-many django-views django-urls

我是Django的新手,现在已经坚持了几天。希望在这里找到一些帮助。我已经搜索了stackoverflow并阅读了django文档但是还没有能够掌握这一点。我使用的是Django 1.6.2和Python 2.7。

我正在设置一个简单的新闻应用,其中文章类别具有 ManyToMany 关系。我在尝试显示特定类别的文章时遇到了麻烦。我有索引工作显示所有文章,并且单页面视图正在工作,例如点击索引中的文章标题会带您进入文章本身。在文章中,我将显示文章类别。到目前为止一切都很顺利。当我尝试链接类别并显示该类别中所有帖子的索引时,我会为网址' category-archive'获得 NoReverseMatch

我应该在像我尝试的观点中这样做,还是经理会更好地工作?打开所有建议和答案。就像我说我是新人所以想知道最佳实践。这是我的代码,并提前感谢您处理noobie。

models.py

from django.db import models
from tinymce import models as tinymce_models

    class ArticleManager(models.Manager):
        def all(self):
        return super(ArticleManager, self).filter(active=True)

    class Category(models.Model):
        title = models.CharField(max_length=65)
        slug = models.SlugField()

    def __unicode__(self, ):
        return self.title

    class Article(models.Model):
        title = models.CharField(max_length=65)
        slug = models.SlugField()
        description = models.CharField(max_length=165)
        content = tinymce_models.HTMLField()
        categories = models.ManyToManyField(Category)
        image = models.ImageField(upload_to='article/images')
        active = models.BooleanField(default=False)
        timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
        updated = models.DateTimeField(auto_now=True, auto_now_add=False)

    objects = ArticleManager()

    def __unicode__(self, ):
        return self.title
    class Meta:
        ordering = ['-timestamp',]

views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, RequestContext, get_object_or_404

from .models import Article, Category

def all_articles(request):
    articles = Article.objects.all()
     return render_to_response('news/all.html', locals(),   context_instance=RequestContext(request))

def single_article(request, slug):
    article = get_object_or_404(Article, slug=slug)
    return render_to_response('news/single.html', locals(), context_instance=RequestContext(request))

def category_archive(request, slug):
    articles = Article.objects.filter(category=category)
    categories = Category.objects.all()
    category = get_object_or_404(Category, slug=slug)
    return render_to_response('news/category.html', locals(),    context_instance=RequestContext(request))

single.html - 适用于单篇文章视图

{% extends 'base.html' %}
{% block content %}

    <h1>{{ article.title }}</h1>
    <img src='{{ MEDIA_URL }}{{ article.image }}' class="article-image img-responsive"/>
    <p>{{ article.content|safe }}</p>
    <p class='small'>
**this next line gets an error for the url 'category-archive'**
    {% for category in article.categories.all %}Category: <a href='{% url "category-archive" %}{{ category.slug }}'>{{ category }}</a>{% endfor %}</p>

{% endblock %}

category.html - 显示特定类别的所有文章

{% extends 'base.html' %}


{% block content %}

    {% for article in articles %}
    <h1><a href='{% url "articles" %}{{ article.slug }}'>{{ article }}</a></h1>
    <a href='{% url "articles" %}{{ article.slug }}'><img src='{{ MEDIA_URL }}{{ article.image }}' class="img-responsive"/></a>
    {{ article.description }}

    {% if forloop.counter|divisibleby:4 %}
     <hr/>
    <div class='row'>
    {% endif %}
    {% endfor %}
    </div>

{% endblock %}

urls.py - 项目网址

from django.conf.urls import patterns, include, url 
from django.conf import settings
from filebrowser.sites import site

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',


(r'^tinymce/', include('tinymce.urls')),
(r'^admin/filebrowser/', include(site.urls)),
(r'^grappelli/', include('grappelli.urls')),

(r'^static/(?P<path>.*)$', 'django.views.static.serve',{
    'document_root': settings.STATIC_ROOT
    }),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{
    'document_root': settings.MEDIA_ROOT
    }),

url(r'^admin/', include(admin.site.urls)),    
url(r'^$', 'dl.views.home', name='home'),
(r'^news/', include('news.urls')),
(r'^guides/', include('guides.urls')),


)

urls.py - 新闻网址

from django.conf import settings
from django.conf.urls import patterns, include, url


urlpatterns = patterns('news.views',
    url(r'^$', 'all_articles', name='articles'),
    url(r'^(?P<slug>[-\w]+)/$', 'single_article'),
**This next one is giving me the problem I suspect - should be url to category with articles**
    url(r'^chive/(?P<slug>[-\w]+)/?', 'category_archive', name='category-archive'),

)

1 个答案:

答案 0 :(得分:4)

我会发布它作为评论,但我没有声誉。 我认为,问题是URL Dispatcher期望category-archive也能获得slug。所以你应该将模板中的URL更改为:

{% url "category-archive" category.slug %}

希望这有帮助!