sitemap.xml empty for static urls in Django - django

I have a Django project and I am trying to create a sitemap for my static urls (no Models). However, when running python manage.py runserver and going to http://127.0.0.1:8000/sitemap.xml, I get it empty:
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>
My code looks like this:
#urls.py
from main_app.sitemaps import StaticSitemap
sitemaps = {
'static': StaticSitemap(),
}
urlpatterns = [
...
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}),
...
]
urlpatterns += i18n_patterns(
...
)
and
#sitemaps.py
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
class StaticSitemap(Sitemap):
priority = 0.5
changefreq = 'weekly'
i18n = True
def location(self, item):
return reverse(item)
The documentation shows an example with Models and it modifies the function items; but since I do not have, I am not sure if I am missing something there.
What am I doing wrong?

I just found out what the problem was.
It seems that you need to define the function items anyway.
def items(self):
list_of_url_names = ['home', 'about', ..., 'contact']
return list_of_url_names
and then sitemap.xml is not empty anymore.

Related

Rendering new custom html templates in existing Django project

I'm not a Django expert but I need to make customizations of this software which is written in Django using the rest framework.
I need to render a custom html template let's say a.html, however when I go to http://localhost:8080/custom/custom/a I get redirected back to different page - not a.html.
This is what I've done so far. I created a new folder in apps called custom:
cvat
apps
custom
templates
custom
_init.py
a.html, b.html, ...
urls.py
apps.py
from django.apps import AppConfig
class CustomConfig(AppConfig):
name = 'cvat.apps.custom'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('custom/<str:name>', views.CustomView),
]
views.py
from django.shortcuts import render
def CustomView(request, name):
return render(request, 'custom/'+name+'.html')
In addition, I have modified these existing files to add the custom folder that was created in apps:
in urls.py added my url patterns:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('cvat.apps.engine.urls')),
path('django-rq/', include('django_rq.urls')),
path('custom/', include('cvat.apps.custom.urls')),
]
in base.py added this:
INSTALLED_APPS = [
...
'cvat.apps.custom'
]
Any advice on what I'm doing wrong?
You can try something like this
url can be like this
urlpatterns = [
path('custom/<name>/', views.CustomView),
]
and your view should be like this.
def CustomView(request, name):
return render(request, f'custom/{name}.html')
Hope this will help you.

How to add Trailing slash (/) in url of sitemap Django?

I want to add (/) in site map of Django. I have used following code to generate sitemap in django
my url.py is
from django.contrib.sitemaps.views import sitemap
from myApp.sitemaps import staticSitemap , mySitemap
sitemaps = {
'staticSitemap':staticSitemap,
'mySitemap':mySitemap
}
urlpatterns = [
path('admin/', admin.site.urls),
path('sitemap.xml', sitemap, {'sitemaps': sitemaps} ),
path('<slug:slug>/',apps.switcher, name='calc_detail'),
]
my sitemap file is like below
from django.contrib.sitemaps import Sitemap
from django.shortcuts import reverse
from .models import SingleCalculator
class staticSitemap(Sitemap):
changefreq = "weekly"
priority = 0.9
def items(self):
return ['home','about','contact','privacy']
def location(self, item):
return reverse(item)
class mySitemap(Sitemap):
changefreq = "weekly"
priority = 0.7
def items(self):
return SingleCalculator.objects.all()
def lastmod(self,obj):
return obj.lastmod
Sitemap is generating now like following URL in loc
<loc>https://sitename.com/absolute-difference-calculator</loc>
I want (/) after the end of url. How can I do this?
In model class SingleCalculator add get_absolute_url function:
def get_absolute_url(self):
return f'/{self.slug}/'

How to fix the problem of not showing the sitemap in django?

I created a sitemap as follows, but nothing is displayed inside the sitemap URL.
How can I fix the problem?
Thank you
setting.py
INSTALLED_APPS = [
'django.contrib.sitemaps',
]
sitemaps.py
from django.contrib.sitemaps import Sitemap
from django.shortcuts import reverse
from riposts.models import Posts
class RiSitemap(Sitemap):
priority = 0.5
changefreq = 'daily'
def get_queryset(self):
posts = self.kwargs.get('posts')
return Posts.objects.filter(status="p")
def lastmod(self, obj):
return obj.updated
def location(self, item):
return reverse(item)
urls.py
from django.contrib.sitemaps.views import sitemap
from .views import home_page
from riposts.sitemaps import RiSitemap
sitemaps = {
'posts':RiSitemap,
}
urlpatterns = [
path('', home_page, name="home"),
path("sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="sitemap"),
]
sitemap image

Django Oscar change URL pattern

I have setup a django-oscar project and I'm trying to configure the URLs. My goal is to change /catalogue to /catalog.
As per the documentation I've added app.py in myproject/app.py
myproject/app.py
from django.conf.urls import url, include
from oscar import app
class MyShop(app.Shop):
# Override get_urls method
def get_urls(self):
urlpatterns = [
url(r'^catalog/', include(self.catalogue_app.urls)),
# all the remaining URLs, removed for simplicity
# ...
]
return urlpatterns
application = MyShop()
myproject/urls.py
from django.conf.urls import url, include
from django.contrib import admin
from . import views
from .app import application
urlpatterns = [
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^admin/', admin.site.urls),
url(r'', application.urls),
url(r'^index/$',views.index, name = 'index'),
]
The project server runs without any error, but when I try localhost:8000/catalog I get
NoReverseMatch at /catalog/ 'customer' is not a registered namespace.
The expected output is localhost:8000/catalog should return the catalogue page.
You can try this
in app.py
from django.conf.urls import url, include
from oscar import app
class MyShop(app.Shop):
# Override get_urls method
def get_urls(self):
urls = [
url(r'^catalog/', include(self.catalogue_app.urls)),
# all the remaining URLs, removed for simplicity
# ...
]
urls = urls + super(MyShop,self).get_urls()
return urls
application = MyShop()
And in your urls.py
you can simply add this
from myproject.app import application as shop
url(r'', shop.urls),
Hope it help for you
Expanding on c.grey's answer to specify how to replace instead of add the urls -
from django.conf.urls import url, include
from oscar import app
class MyShop(app.Shop):
def get_urls(self):
urls = super(MyShop, self).get_urls()
for index, u in enumerate(urls):
if u.regex.pattern == r'^catalogue/':
urls[index] = url(r'^catalog/', include(self.catalogue_app.urls))
break
return urls
application = MyShop()
You need to include the URLs, not reference them directly.
url(r'', include('application.urls')),

Django sitemap index example

I have following models relation:
class Section(models.Model):
section = models.CharField(max_length=200, unique=True)
name = models.CharField(max_length=200, blank = True)
class Article (models.Model):
url = models.CharField(max_length = 30, unique=True)
is_published = models.BooleanField()
section = models.ForeignKey(Section)
I need to create a sitemap for articles, which contains sitemap files for sections. I was reading django documentation about it here http://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/
But didn't manage to find answer how can I:
Define sitemap class in this case
How can I pass section parameters into url file (as it's explained in
the docs)
From where can I get {'sitemaps': sitemaps} if I defined
sitemap as a python class in another file in the application
If i understand correctly you want to use sitemap index that would point at seperate sitemap xml files each for every section.
Django supports this feature by providing a separate sitemap view for index sitemaps.
Haven't used that feature before but something like the following would probably work in your case.
### sitemaps.py
from django.contrib.sitemaps import GenericSitemap
from models import Section
all_sitemaps = {}
for section in Section.objects.all():
info_dict = {
'queryset': section.article_set.filter(is_published=True),
}
sitemap = GenericSitemap(info_dict,priority=0.6)
# dict key is provided as 'section' in sitemap index view
all_sitemaps[section.name] = sitemap
### urls.py
from sitemaps import all_sitemaps as sitemaps
...
...
...
urlpatterns += patterns('',
(r'^sitemap.xml$', 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}),
(r'^sitemap-(?P<section>.+)\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)
Django==2.2
Python==3.6
Here is the better and easy way to use sitemap index in Django,
install django.contrib.sitemaps in the project by adding it to INSTALLED_APPS of settings.py.
Write sitemaps.py file in your apps and define classes as you need. Example extend django.contrib.sitemap.Sitemap in StaticViewSitemap sitemap class for static URLs, make sure your all static URL has the name for reverse lookup(getting URL from URL name)
# app/sitemap.py
from django.contrib import sitemaps
from django.urls import reverse
class StaticViewSitemap(sitemaps.Sitemap):
priority = 0.6
changefreq = 'monthly'
def items(self):
# URLs names
return ['index', 'aboutus', 'ourstory',]
def location(self, item):
return reverse(item)
Import all sitemaps in urls.py
import sitemap and index from django.contrib.sitemaps.views
then create a dictionary with sitemaps
# urls.py
from django.contrib.sitemaps.views import sitemap, index
from app.sitemaps import StaticViewSitemap
# add as many as sitemap you need as one key
sitemaps = {
"static" : StaticViewSitemap,
}
urlpatterns = [
# sitemap.xml index will have all sitemap-......xmls index
path('sitemap.xml', index, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.index'),
# sitemap-<section>.xml here <section> will be replaced by the key from sitemaps dict
path('sitemap-<section>.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
]
Here you will have two sitemaps 1. sitemaps.xml 2. sitemaps-static.xml
Run server open URL: http://localhost:8000/sitemap.xml
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>http://127.0.0.1:8000/sitemap-static.xml</loc>
</sitemap>
</sitemapindex>
Django automatically created an index of sitemaps now open URL: http://127.0.0.1:8000/sitemap-static.xml
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://localhost:8000/</loc>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>http://localhost:8000/about-us</loc>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>http://localhost:8000/our-story</loc>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
</urlset>
For me, the accepted answer was impacting development and testing cycle speed since it made python manage.py commands run more slowly -- I had a little more to do in the DB than this example.
Here are the changes I made to mitigate (adapted to the example). Have yet to battle test it but this seems to do the trick (Python3):
### sitemaps.py
class SitemapLookup():
"""
Instantiated class replaces the dictionary of {'sitemap-section': Sitemap} for urls.py
Speeds up application load time by only querying the DB when a sitemap is first requested.
"""
def __init__(self):
self.sitemaps = {}
def __iter__(self):
self._generate_sitemaps_dict()
return self.sitemaps.__iter__()
def __getitem__(self, key):
self._generate_sitemaps_dict()
return self.sitemaps[key]
def items(self):
self._generate_sitemaps_dict()
return self.sitemaps.items()
def _generate_sitemaps_dict(self):
if self.sitemaps:
return
for section in Section.objects.all():
info_dict = {
'queryset': section.article_set.filter(is_published=True),
}
# dict key is provided as 'section' in sitemap index view
self.sitemaps[section.name] = GenericSitemap(info_dict, priority=0.6)
### urls.py
from sitemaps import SitemapLookup
...
...
...
sitemaps = SitemapLookup()
urlpatterns += patterns('',
(r'^sitemap.xml$', 'django.contrib.sitemaps.views.index', {'sitemaps': sitemaps}),
(r'^sitemap-(?P<section>.+)\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)