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."
Just in case you do not know why it is called reverse : It takes an input of a url name and gives the actual url, which is reverse to having a url first and then give it a name.
the reverse function allows to retrieve url details from url's.py file through the name value provided there. This is the major use of reverse function in Django. The redirect variable is the variable here which will have the reversed value. So the reversed url value will be placed here.
reverse_lazy() It is useful for when you need to use a URL reversal before your project's URLConf is loaded. Some common cases where this function is necessary are: providing a reversed URL as the url attribute of a generic class-based view.
Reverse_lazy is, as the name implies, a lazy implementation of the reverse URL resolver. Unlike the traditional reverse function, reverse_lazy won't execute until the value is needed. It is useful because it prevent Reverse Not Found exceptions when working with URLs that may not be immediately known.
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With