本文介绍了反向网址问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义为

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使用相同的一种定义,而我的使用

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

w ^我一直得到的那顶帽子是一个错误,指出

What I keep getting is an error that states

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


推荐答案

给出网址名称:

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

这篇关于反向网址问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 04:14