Django Class Based查看CreateView网址解析

时间:2014-01-05 00:59:59

标签: django django-models django-views django-urls django-class-based-views

我对CBV很新,并试图弄清楚它。我从django doc页面复制了以下示例:

https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-editing/

models.py

from django.core.urlresolvers import reverse
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=200)

    def get_absolute_url(self):
        return reverse('author-detail', kwargs={'pk': self.pk})

views.py

from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from myapp.models import Author

class AuthorCreate(CreateView):
    model = Author
    fields = ['name']

class AuthorUpdate(UpdateView):
    model = Author
    fields = ['name']

class AuthorDelete(DeleteView):
    model = Author
    success_url = reverse_lazy('author-list')

urls.py

from django.conf.urls import patterns, url
from myapp.views import AuthorCreate, AuthorUpdate, AuthorDelete

urlpatterns = patterns('',
    # ...
    url(r'author/add/$', AuthorCreate.as_view(), name='author_add'),
    url(r'author/(?P<pk>\d+)/$', AuthorUpdate.as_view(), name='author_update'),
    url(r'author/(?P<pk>\d+)/delete/$', AuthorDelete.as_view(), name='author_delete'),
)

在author / add /我确实得到了表单,但是当我输入字符串时出现以下错误:

Reverse for 'author-detail' with arguments '()' and keyword arguments '{'pk': 3}' not found.

似乎新条目已添加到数据库中,但它无法解析下一个视图的URL?

所以我很困惑,这个get_absolute_url()对象的方法应该做什么,它是如何工作的(我无法从django doc中掌握它)以及如何解决这个问题? 感谢。

编辑1:添加了模板:

author_form.html:

<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create" />
</form>

1 个答案:

答案 0 :(得分:4)

默认情况下,创建新模型时,django会将您重定向到get_absolute_url方法返回的模型绝对URL。在您的示例中,您需要添加一个名为author-detail的网址,该网址接受pk关键字参数。

urlpatterns = patterns('',
  # ...
  url(r'author/(?P<pk>\d+)/$', AuthorDetail.as_view(), name='author-detail'),
)

请注意,网址名称与get_absolute_url方法中的视图名称相匹配。

在模板中使用它:

{% for author in authors %}
  <a href="{{author.get_absolute_url}}">{{author.name}}</a>
{% endfor %}