反向URL问题

时间:2013-07-24 03:31:09

标签: python django url django-views reverse

我有一个定义为

的django模型
from utils.utils import APIModel
from django.db import models
from django.core.urlresolvers import reverse

class DjangoJobPosting(APIModel):
    title = models.CharField(max_length=50)
    description = models.TextField()
    company = models.CharField(max_length=25)

    def get_absolute_url(self):
        return reverse('jobs.views.JobDetail', args=[self.pk])
带视图的

from restless.views import Endpoint
from restless.models import serialize
from .models import *
from utils.utils import JSON404

import ujson as json

class JobList(Endpoint):
    def get(self, request):
        fields = [
            ('url', lambda job: job.get_absolute_url()),
            'title',
            ('description',lambda job: job.description[:50]),
            'id'
        ]
        jobs = DjangoJobPosting.objects.all()
        return serialize(jobs, fields)

class JobDetail(Endpoint):
    def get(self, request, pk):
        try:
            job = DjangoJobPosting.objects.get(pk=pk)
            print(job)
            fields = ["title","description","company","id"]
            return serialize(job,fields)
        except Exception as e:
            return JSON404(e)

我在其他关于反向方法的帖子中看到的是,他们在我上面指定的术语中定义了第一个反向参数,但是他们的urls.py使用相同类型的定义,而我的使用

from django.conf.urls import patterns, include, url
from .views import *

urlpatterns = patterns('',
    url(r'^$',JobList.as_view()),
    url(r'^(?P<pk>\d+)/$', JobDetail.as_view()),
)

我不断得到的是一个错误,表明

"Reverse for 'jobs.views.JobDetail' with arguments '(1,)' and keyword arguments '{}' not found."

1 个答案:

答案 0 :(得分:8)

提供网址名称:

from django.urls import reverse

urlpatterns = patterns('',
    url(r'^$',JobList.as_view(), name='joblist'),
    url(r'^(?P<pk>\d+)/$', JobDetail.as_view(), name='jobdetail'),
)

致电reverse时使用该名称:

return reverse('jobdetail', args=[self.pk])

return reverse('jobdetail', kwargs={'pk': self.pk})