How to add Trailing slash (/) in url of sitemap Django? - 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}/'

Related

Django Sitemap is not working gives error "Reverse for 'index' not found. 'index' is not a valid view function or pattern name."

I'm trying to implement a Sitemap for my app and I get the error
"Reverse for 'index' not found. 'index' is not a valid view function or pattern name."
even though these views are set up.
What could cause this? I have no problem with dynamic sitemaps, just the static one.
My views.py
def front_page(request):
return render(request, 'django_modules_testing_app/front_page.html', {})
def about_us(request):
return render(request, 'ihgr_app/about_us.html', {})
def index(request):
return render(request, 'django_modules_testing_app/index.html', {})
urls.py
from django.urls import path
from . import views
from . import blocks
from django.contrib.sitemaps.views import sitemap
from .sitemaps import DjangoModulesTestingApp
app_name = 'django_modules_testing_app'
sitemaps = {
'main_app':DjangoModulesTestingApp
}
urlpatterns = [
path('', views.front_page, name='front_page'),
path('', views.index, name='index'),
path('', views.about_us, name='about_us'),
path('category_details/<slug:slug>/', blocks.category_details, name='category_details'),
path('search_website/', views.SearchWebsite.as_view(), name='search_website'),
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap')
]
sitemaps.py
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
class StaticSitemap(Sitemap):
changefreq = 'weekly'
priority = 0.8
protocol = 'http'
def items(self):
return ['front_page','index','about_us']
def location(self, item):
return reverse(item)
You've to specify your app name inside reverse(...) like this
class StaticSitemap(Sitemap):
changefreq = 'weekly'
priority = 0.8
protocol = 'http'
def items(self):
return ['front_page','index','about_us']
def location(self, item):
return reverse(f"django_modules_testing_app:{item}")

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 is not showing the right path when clicking on a link

This is what it shows when you click on the link
Page not found (404)
Request Method: GET Request URL:
http://localhost:8000/jobapplication/new/1
Using the URLconf defined in careal.urls, Django tried these URL
patterns, in this order:
^$ [name='landing-index']
^admin/
^accounts/
^taskmanager/
^login/$ [name='login']
The problem is that I don't know why it is opening the link as http://localhost:8000/jobapplication/new/1, when it should be http://localhost:8000/taskmanager/jobapplication/new/1
This is what I have in the urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.contrib.auth import views as auth_views
from landingpage import views as landingpage_views
urlpatterns = [
url(r'^$', landingpage_views.index, name='landing-index'),
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^taskmanager/', include('taskmanager.urls')),
url(r'^login/$', auth_views.login, name='login'),
]
This is in urls.py in the app taskmanager
from django.conf.urls import url
from . import views
from taskmanager.views import *
app_name = 'taskmanager'
urlpatterns = [
# Task manager urls
url(r'^$', JobApplicationIndex.as_view(), name='index'),
url(r'jobapplication/add/(?P<jobpost_id>[0-9]+)/$', JobApplicationCreate.as_view(), name='jobapplication-add'),
url(r'jobapplication/new/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationAdd, name='jobapplication-new'),
url(r'jobapplication/edit/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationEdit, name='jobapplication-edit'),
url(r'jobapplication/edit/(?P<pk>[0-9]+)/$', JobApplicationUpdate.as_view(), name='jobapplication-edit'),
url(r'^jobapplication/(?P<pk>[0-9]+)/$', JobApplicationDetails.as_view(), name='jobapplication-detail'),
# Company urls
url(r'company/$', CompanyIndex.as_view(), name='company-index'),
url(r'company/add/$', CompanyCreate.as_view(), name='company-add'),
url(r'^company/(?P<pk>[0-9]+)/$', CompanyDetails.as_view(), name='company-detail'),
# Job Post urls
url(r'jobpost/$', JobPostIndex.as_view(), name='jobpost-index'),
url(r'^jobpost/(?P<pk>[0-9]+)/$', JobPostDetails.as_view(), name='jobpost-detail'),
# Statistics urls
url(r'^kpi/$', views.kpi, name='kpi'),
]
And this is what I have in views.py in taskmanager, related to jobapplication
# Job Application views
class JobApplicationIndex(generic.ListView):
template_name = 'taskmanager/jobapplication_index.html'
def get_queryset(self):
if self.request.user.is_authenticated:
return JobApplication.objects.filter(user=self.request.user.id).order_by('-created_at')
class JobApplicationCreate(CreateView):
model = JobApplication
fields = ['jobpost', 'sent_date', 'deadline', 'success_rate']
def get_initial(self):
jobpost = get_object_or_404(JobPost, id=self.kwargs.get('jobpost_id'))
return {
'jobpost':jobpost,
}
def form_valid(self, form):
form.instance.user = self.request.user
return super(JobApplicationCreate, self).form_valid(form)
class JobApplicationDetails(generic.DetailView):
model = JobApplication
class JobApplicationEdit(UpdateView):
model = JobApplication
#fields = ['jobpostid', 'is_favorite']
#p = JobApplication.objects.get(id=jobpostid)
#p.is_favorite = is_favorite
#p.save()
class JobApplicationUpdate(UpdateView):
model = JobApplication
fields = ['sent_date', 'deadline', 'success_rate']
template_name_suffix = '_update_form'
def JobApplicationAdd(request, jobpost_id):
if request.method == 'GET' and request.user.is_authenticated:
# If job app for this id exists, redirect to that job app page with a message
if JobApplication.objects.filter(jobpost_id=int(jobpost_id)).exists():
existing = JobApplication.objects.get(jobpost_id=int(jobpost_id))
messages.add_message(request, messages.INFO, 'An application for this opening already exists.')
return HttpResponseRedirect(reverse('taskmanager:jobapplication-detail', args=[existing.id]))
jobapp = JobApplication(user=request.user, jobpost_id=int(jobpost_id), success_rate=50)
jobapp.save()
return HttpResponseRedirect(reverse('taskmanager:index'))
--- The thing is all the other links in taskmanager work and when you click on them, the right path is opened Eg: -
- http://localhost:8000/taskmanager/jobpost/
- http://localhost:8000/taskmanager/jobpost/2/
- http://localhost:8000/taskmanager/company/2/
- http://localhost:8000/taskmanager/kpi/
Try Adding an uptick in front of the regex patterns like you did for the ones that are working.
from django.conf.urls import url
from . import views
from taskmanager.views import *
app_name = 'taskmanager'
urlpatterns = [
# Task manager urls
url(r'^$', JobApplicationIndex.as_view(), name='index'),
url(r'^jobapplication/add/(?P<jobpost_id>[0-9]+)/$', JobApplicationCreate.as_view(), name='jobapplication-add'),
url(r'^jobapplication/new/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationAdd, name='jobapplication-new'),
url(r'^jobapplication/edit/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationEdit, name='jobapplication-edit'),
url(r'^jobapplication/edit/(?P<pk>[0-9]+)/$', JobApplicationUpdate.as_view(), name='jobapplication-edit'),
url(r'^jobapplication/(?P<pk>[0-9]+)/$', JobApplicationDetails.as_view(), name='jobapplication-detail'),
# Company urls
url(r'^company/$', CompanyIndex.as_view(), name='company-index'),
url(r'^company/add/$', CompanyCreate.as_view(), name='company-add'),
url(r'^company/(?P<pk>[0-9]+)/$', CompanyDetails.as_view(), name='company-detail'),
# Job Post urls
url(r'^jobpost/$', JobPostIndex.as_view(), name='jobpost-index'),
url(r'^jobpost/(?P<pk>[0-9]+)/$', JobPostDetails.as_view(), name='jobpost-detail'),
# Statistics urls
url(r'^kpi/$', views.kpi, name='kpi'),
]

sitemap.xml empty for static urls in 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.

sitemaps.xml not working in google app engine or local google sdk but it does work running in django 1.9.7 server

In the following image on the left side is the google server and on the right side is the django server:
The google server does not show any logs about it, at first sight, the xml is rendered by the server but it doesn't show the links of the sitemap,
sitemap.py
from django.contrib.sitemaps import Sitemap
from django.core.urlresolvers import reverse
from datetime import datetime
class BasicSitemap(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.now()
def location(self, obj):
return reverse(obj)
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
from django.shortcuts import render_to_response
from django.template import RequestContext
from sitemap import BasicSitemap
from django.contrib.sitemaps.views import sitemap
sitemaps = {
'pages': BasicSitemap(['about', 'home', 'team', 'contacto', 'courses', 'services'])
}
urlpatterns = [
url(r'^', include('apps.home.urls')),
url(r'^', include('apps.about.urls')),
url(r'^', include('apps.contact.urls')),
url(r'^', include('apps.services.urls')),
url(r'^', include('apps.team.urls')),
url(r'^', include('apps.client.urls')),
url(r'^', include('apps.course.urls')),
url(r'^admin/', admin.site.urls),
url('^robots.txt', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')),
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap')
]
def handler404(request):
response = render_to_response('404.html', {},
context_instance=RequestContext(request))
response.status_code = 404
return response
def handler500(request):
response = render_to_response('500.html', {},
context_instance=RequestContext(request))
response.status_code = 500
return response
Things I've done:
run the aplication in different os (linux windows)
tried different django versions < 1.9.7
The weird thing about this is that I had a prev version of this site wich was deployed at January this year and it doesn't have that problem, I used logic, but this new app engine seems to work differently.
Any ideas?? a link to the sitemap page