使用ForeignKey模型的Django视图

时间:2016-11-08 09:34:16

标签: python django django-models django-views

我已经关注了 models.py:

class ArticleCategory(models.Model):
    category_name = models.CharField("Category", max_length=200, unique=True)
    slug = models.SlugField(null=True, blank=True, unique=True)

    def get_data(self):
        return {
            "id": self.pk,
            "category_name": self.category_name,
            "slug": self.slug,
        }

class Article(models.Model):
    category = models.ForeignKey(ArticleCategory)
    ...

    def get_data(self):
        return {
            "id": self.pk,
            ...
        }

views.py:

def articles(request, *args, **kwargs):
    context = {
        'categories': ArticleCategory.objects.all(),
        'articles': Article.objects.filter(category__id=2)
    }
    return render(request, 'wellness.html', context)

一切正常。但是,我希望category__id是动态的,所以我将函数更改为def articles(request, id, *args, **kwargs)'articles': Article.objects.filter(category__id=id) 好像它正在为我以前的项目工作,但现在每次我尝试设置这样的行为时都会抛出该错误(尝试过id,slug,category_name):

Exception Type:     TypeError
Exception Value:    articles() takes at least 2 arguments (1 given)
Exception Location:     .../env/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py in _wrapped_view, line 23

也许是urls.py?

from django.contrib.auth.decorators import login_required
...

urlpatterns = [
    ...
    url(r'^wellness$', login_required(articles), name='wellness'),
    ...
]

1 个答案:

答案 0 :(得分:2)

是的,确实存在于你的urls.py中。

您定义了一个视图,该视图需要两个参数但未配置url函数来捕获部分网址并将其作为request旁边的附加参数传递。

你想做这样的事情来分别捕获一个slug或id:

蛞蝓

from django.conf.urls import url

urlpatterns = [
    url(r'^wellness/(?P<slug>[-\w]+)/?$', login_required(articles), name='wellness'),
    url(r'^reports/(?P<id>[0-9]+)/$', credit_views.report),# kwargs = {"id": 9}
]

或者使用id:

urlpatterns = [
    url(r'^wellness/(?P<id>[0-9]+)/$', login_required(articles), name='wellness'),
]

documentation中,您可以找到更多信息。