Reverse URL issue

2019-06-27 08:46发布

I have a django model defined as

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])

with a view

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)

What I have seen in other posts which talk about reverse method is that they define the first reverse parameter in the terms I specified above, but their urls.py uses the same kind of definition, while mine uses

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()),
)

What I keep getting is an error that states

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

1条回答
Melony?
2楼-- · 2019-06-27 09:33

Give urls names:

from django.urls import reverse

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

Use that name when call reverse:

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

or

return reverse('jobdetail', kwargs={'pk': self.pk}) 
查看更多
登录 后发表回答