I am currently trying to generate a sitemaps.xml using Django. To do that, i followed the Django documentation but I have troubles to generate the sitemaps for the following type of urls :
url(r'^duo/(?P<pseudo>[a-z]+)/$','clients.views.duo', name='duo')
My sitemaps.py is looking like that :
from django.contrib import sitemaps
from django.core.urlresolvers import reverse
from datetime import datetime
class SiteSitemap(sitemaps.Sitemap):
def __init__(self, names):
self.names = names
def items(self):
return self.names
def changefreq(self, obj):
return 'weekly'
def location(self, obj):
return reverse(obj)
and the part containing the sitemaps in urls.py like that:
sitemaps = {
'pages':SiteSitemap(['homepage',
'landing_page',
'mentions',
'no_anim',
]),
}
urlpatterns += [
url(r'^sitemap\.xml', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
]
When passing 'duo' on its own, I have the following error:
NoReverseMatch at /sitemap.xml
Reverse for 'duo' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['duo/(?P<pseudo>[a-z]+)/$']
and when I try to pass arguments in this way ('duo', 'anna'), I have the error:
NoReverseMatch at /sitemap.xml
Reverse for '('duo', 'anna')' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I am encountering a syntax error which is rather logic as reverse() does not accept triple parenthesis. However, I do not see how I can fix this. Does anyone have a clue about it ?
In this case, the correct syntax for using reverse is:
reverse('duo', args=['anna'])
Redefine your location method to following :
def location(self, item):
return reverse('url_name', args=(arg,))
Using the previous answers, I did this little piece of code, hope it can be of any help for others users:
def location(self, obj):
if len(obj) == 1:
return reverse(obj[0])
else:
return reverse(obj[0],args=[obj[1]])
obj are tuple objects declared in urls.py
Related
I am getting NoReverseMatch when routing to a specific path.
It is not able to find the primary key <int:pk> for only one urlpattern while getting results for all other similar paths.
I am assuming this error is because the model here is different, ex,
Not getting error for:
class PostUpdateView():
model = A
and the error I am getting is for:
class AddCommentView():
model = B
urlpatterns = [
path('post/<int:pk>/update/', PostUpdateView.as_view(), name = 'post-update'),
path('post/<int:pk>/comment', AddCommentView.as_view(), name = 'post-comment')]
Both classes are in same views.py file because I need model A's primary key in my routing url so that I can reverse to the original page.
Error:
Reverse for 'post-comment' with no arguments not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/comment$']
What is the correct way to include both models' keys in same route?
Note: A's primary key is present in B as foreign key.
You get_absolute_url method should look like this the kwargs argument.
from django.urls import reverse
class AddCommentView():
model = B
def get_absolute_url(self):
return reverse('post-comment', kwargs={'pk': self.pk})
I have a little question about request attribute in my function located in a python file (not my view):
def my_function(model, request):
instance = model.objects.filter(application=request.cur_app, display=True).order_by('order')
return instance
In this same file, I call my function like this:
for element in my_function(my_model):
... do something ...
But I get this issue:
my_function() missing 1 required positional argument: 'request'
I don't understand How I can solve this issue, because if I add 'request' in my loop, I get:
name 'request' is not defined
Thank you !
Update:
I have a middleware.py file which contains this:
class MultiSiteMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.cur_app = WebApplication.objects.get_current(request)
return self.get_response(request)
And this is this middleware that I want to get in my menu.py file in this function:
def list_of_edition():
""" Return list of editions
:return queryset
"""
instance = NavbarMenuSettings.objects.filter(application=MultiSiteMiddleware, display=True).order_by('order')
return instance
When you run this function
my_function
you must given two params model and request
model = ...
request = ...
my_function(model,request)
django function base view 1st positional argument is request,
def funtionbaseview(request, arg1, arg2)
I'm learning django and i'm trying to create my own custom class in a views.py file
This class i would use have to method, one for classical HTML rendering, and another for json response
my class in views.py
class myListView():
context = {}
def __init__(self, request):
request = request
context['PageTitle'] = 'Contacts'
context['people'] = People.objects.all()
def htmlRender(self, *args, **kwargs):
context['children_template'] = 'people/list.html'
return render(request,'base.html',context)
def jsonRender(self, *args, **kwargs):
return HttpResponse(json.dumps(self.context['people']), content_type="application/json")
my urls.py
path('list', login_required(myListView.htmlRender()), name='list'),
path('list/json', login_required(myListView.jsonRender()), name='list'),
Here is the error sended by debugger :
TypeError: htmlRender() missing 1 required positional argument: 'self'
I don't have any idea how to solve this, maybe i'm dreaming about using custom class in view ?
Thanks'you
from django.views.generic import ListView
class myListView(ListView):
Maybe you are not extending the ListView Class, try this out.
You should first create an instance from "myListView" class then use it :
myListViewInstance = myListView(arguments)
myListViewInstance.htmlRender()
I am trying to set GET parameters on a LinkColumn based on Accessors with django-tables2.
Let's say:
urls.py
urlpatterns = [
...
url(r'^rqGET$', views.rqGET, name='rqGET'),
...
]
views.py
def rqGET(request):
#... do something with request.GET
tables.py
class MyTable(tables.Table):
id = LinkColumn('rqGet',text='Link') # do something with Accessors to make a GET string, maybe ?id=A('pk')
class Meta:
model = MyModel #(has field 'id')
I want to use reverse to get the correct url, then construct the GET parameter string. For example /rqGET?id=1 ('1' would be different in each row).
That's not really how Accessors work in django-tables2. Django-tables2 uses django's reverse to generate urls. If you want reverse to be able to generate the url, you need to define the parameters in your urls, which will be passed as arguments to your view function:
# urls.py
urlpatterns = [
...
url(r'^rqGET/(?P<id>\d+)$', views.rqGET, name='rqGET'),
...
]
# views.py
def rqGET(request, id):
# do something with request/id.
If you don't want to change the way your url is formatted, you can use a custom render_ function on your MyTable like this:
# tables.py
from django.core.urlresolvers import reverse
class MyTable(tables.Table):
id = LinkColumn('rqGet', text='Link') # do something with Accessors to make a GET string, maybe ?id=A('pk')
class Meta:
model = MyModel
def render_id(self, record):
url = reverse('rqGET')
return format_html('{}', url, record.id, 'Link')
This will render a link with format /rqGET/?id=<id>.
I'm trying to implement django sitemaps but i get the following error. I don't know what I'm doing wrong. Here is the relevant code and traceback.
File "mysite/sitemap.py" in location
20. return reverse(obj)
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in reverse
532. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix
452. (lookup_view_s, args, kwargs, len(patterns), patterns))
Exception Type: NoReverseMatch at /sitemap.xml
Exception Value: Reverse for 'name_of_url' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
here is sitemap.py file
from django.contrib.sitemaps import Sitemap
from django.core.urlresolvers import reverse
from meddy1.models import Doctor
import datetime
class Sitemap(Sitemap):
def __init__(self, names):
self.names = names
def items(self):
return self.names
def changefreq(self, obj):
return 'weekly'
def lastmod(self, obj):
return datetime.datetime.now()
def location(self, obj):
return reverse(obj)
class DoctorSitemap(Sitemap):
changefreq = "Daily"
priority = 1
def items(self):
return Doctor.objects.all()
def lastmod(self, obj):
return obj.date
here is urls.py file
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}),
If you read carefully the documentation:
https://docs.djangoproject.com/en/1.6/ref/contrib/sitemaps/#django.contrib.sitemaps.Sitemap.location
You will find out that Django calls get_absolute_url for the each Sitemap object (unless you have location specified).
You define localtion with: reverse(obj) where does that point exactly? Your reverse should point to a valid registered url. Additionally where exactly did you read that location receives an argument? location is either an attribute or a method that returns a path (no arguments required).
Your error is not sitemaps related, but rather url resolution inside your registered sitemap models.
Finally what is the exact purpose of the Sitemap Class you define?