Page not found: http://127.0.0.1:8000/sitemap.xml/ - django

Here are the codes to create the sitemap for one of my app 'blog' in my site: (using Django 2.0)
settings.py
INSTALLED_APPS += [
'django.contrib.sites',
'django.contrib.sitemaps',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
urls.py
from django.urls import include, path
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import PostSiteMap
sitemaps = {'posts': PostSiteMap}
urlpatterns += [
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap')
]
sitempas.py (under 'blog' app directory)
from django.contrib.sitemaps import Sitemap
from .models import Post
class PostSiteMap(Sitemap):
changefreq = 'weekly'
priority = 0.5
def items(self):
return Post.published.all()
def lastmod(self, obj):
return obj.publish
The sitemap.xml doesn't appear: http://127.0.0.1:8000/sitemap.xml/
There is the url (the eighth) matching my inputted one. Why it says 'not match'?

Your code is good, your environment is what is wrong (maybe you are using the default Django site, that is www.example.com). Change it to a local environment (the typical 127.0.0.1:8000).
To do this in Django you need to do the following:
Check if you are running the local server in your command prompt, if is not, type python manage.py runserver.
go to http://127.0.0.1:8000/admin/sites/site/
Change the default site (typically the default in Django is example.com) to 127.0.0.1:8000. This needs to be done in the domain and display name (while you aren't in a production environment).
Press F5 in your local web page in your browser.
go to your sitemap page (http://127.0.0.1:8000/sitemap.xml)
And voilĂ ! there is your sitemap.

Write full /sitemap.xml like this and try
Enter this url and load page
http://127.0.0.1:8000/sitemap.xml/

The error is
Site matching query does not exist
which means that you have to setup and configure Sites framework.
To enable the sites framework, follow these steps:
Add 'django.contrib.sites' to your INSTALLED_APPS setting.
Define a SITE_ID setting:
SITE_ID = 1
Run migrate.
For more information check documentation.

Related

How to make one view from one app be shown in all urls in Django?

I have created an app for the main template of my project (All other templates inherit from this one). The template includes header, footer and an aside in which i can add and delete posts from the admin panel. Now, when rendering all the templates everything (header, footer and the respective {% block content %}) is shown correctly but not the aside because i'm not passing any url to the view managing it.
I'm trying to pass that view to every URL of my project so the aside is always shown.
I just dont get the way of doing it.
Just to clarify: Following the code i'm going to show now the aside is shown in localhost:8000 only. Not in localhost:8000/inicio nor any other url.
Aside views.py
from django.shortcuts import render
from .models import asides
def post_aside(request):
aside_posts = asides.objects.all()
return render(request, "main/main.html", {"aside_posts" : aside_posts})
urls.py of the app with the aside
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_aside, name='main'),
]
urls.py of the project
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
path('inicio/', include('inicio.urls')),
path('galeria/', include('galeria.urls')),
path('mapa/', include('mapa.urls')),
path('contacto/', include('contacto.urls')),
path('usuarios/', include('usuarios.urls')),
]
urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Create context_processor.py in app where your asides model exists.
Then add inside:
from .models import asides
def website_content(request):
context = {
'aside_posts': asides.objects.all(),
}
return context
Then in your settings.py in context_processors list add on the end:
<your_app>.context_processor.website_content
it should look like:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'aside.context_processor.website_content', # HERE PATH TO YOUR CONTEXT PROCESSOR FUNCTION
],
},
},
]
after this use {% for post in aside_posts %} in your template anywhere you want.

How to get media images in url in django url with reactjs

static and media configuration in settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'frontend','build', 'static')
]
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
urls.py
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
re_path('', TemplateView.as_view(template_name='index.html')),
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
Here i am using django with reactjs.
i have given the path of build folder in react app like this.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'frontend','build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
When i am going to http://127.0.0.1:8000/media/images_OkG6q2k.jpeg path to get images
in side media folder which are uploaded by users i am getting the react route page.
I am not getting the image from media folder.
How i can see the media photos through url.
Project structure
react home is coming instead media image like this when i amgoing url
I think I just overcame this problem with one of my projects with Django backend + React frontend. It is in your url patterns.
As I understand it, this catch-all pattern:
re_path('', TemplateView.as_view(template_name='index.html'))
essentially overrides the media url pattern you wrote (and any others below it), which prevents the Django backend from allowing you to access the media files. To fix this, simply make sure the catch-all route is the last one on your patterns. After you are done with the rest of the patterns, on a new line do this:
urlpatterns += [re_path('', TemplateView.as_view(template_name='index.html'))]
This way, you add it to your paths after all the rest and it doesn't "block" any of the others. hopefully this fixes it!

Django - Tutorial - Setting IndexView but Getting TemplateDoesNotExist

I have searched through all the questions here already on TemplateDoesNotExist.
I have also been troubleshooting this for about 12 hours.
There is something I am not understanding. I am new to django.
I am following the following Thinkster tutorial:
Building Web Applications with Django and AngularJS
Here is the error:
Exception Location: C:\Users\Workstation333\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader.py in select_template, line 47
Exception Type: TemplateDoesNotExist
Exception Value:
index.html
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\Workstation333\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\Workstation333\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\Workstation333\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\templates\index.html (Source does not exist)
This IndexView code I do not understand, and I believe is where the problem lies. The tutorial doesn't go over this code. I think this is what changes the index.html or how to find it. This is inside my views.py and is same project folder where my urls.py is located.
views.py
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.generic.base import TemplateView
from django.utils.decorators import method_decorator
class IndexView(TemplateView):
template_name = 'index.html'
#method_decorator(ensure_csrf_cookie)
def dispatch(self, *args, **kwargs):
return super(IndexView, self).dispatch(*args, **kwargs)
url.py
from django.contrib import admin
from django.urls import path, re_path, include
from rest_framework_nested import routers
from authentication.views import AccountViewSet
from HawkProject.views import IndexView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^api/v1/', include(router.urls)),
re_path(r'^.*$', IndexView.as_view(), name='index')
]
partial settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Please help, and Thank you.
Edit:
I added the following to the code, and I got it to not break right away,
but I don't think it is a solution, but a hack that will break, or is not maintainable. I added the index for the admin index inside Dirs like so:
'DIRS':
['C:/Users/Workstation333/AppData/Local/Programs/Python/Python36/Lib/site-
packages/django/contrib/admin/templates/admin'],
I couldn't find the other index files in the directories where it thinks they should have been. *notice the double admin in the directory above, not sure why that is. It also makes the "home" page take me directly to the admin page.
I haven't read through the tutorial you are doing but try doing this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
As you can see, I think you are getting this error because your template directory 'DIRS' is blank and as such Django does not know where to search for 'index.html'. The 'templates' name can be changed to any name you want but just name it according to the folder which you keep your templates in within each of your apps.
Django Templates

How to set base URL in Django

I would like to run Django from location https://www.example.com/someuri/ so that I have the admin interface at https://www.example.com/someuri/admin/. I can see the login window but when I log in I get redirected to https://www.example.com/admin/.
Where can I set the base URL of Django to https://www.example.com/someuri/? I tried with BASE_URL but with no luck.
#AgileDeveloper's answer is completely correct for that one off case of admin. However, is the desire to set it this way for all URLs? If so, perhaps you should do something like this
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^someuri/', include([
url(r'^admin/', include(admin.site.urls) ),
url(r'^other/$', views.other)
])),
]
I have a project that has a similar setup. I have django running using a virtual environment with apache. In my 000-default.conf file, I set the WSGIScriptAlias to the following:
WSGIScriptAlias /someuri /path/to/wsgi.py
Here is the documentation on WSGIScriptAlias to serve the project from a subdirectory, https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/#using-mod-wsgi-daemon-mode.
Than in the urls.py file I set the following:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^', include('someuri.urls')),
url(r'^admin/', admin.site.urls),
]
After logging in, I am redirected to http://example.com/someuri/admin/
The answer of #James Wallace works well assuming you have control of the web server hosting Django at /someuri. In that configuration, the server will pass a value of SCRIPT_NAME in the header to Django, who will then know it is being served on that sub-path.
However, if you do not have control of the front-end server, then you can force Django to assume that value by adding to settings.py in the project:
USE_X_FORWARDED_HOST = True
FORCE_SCRIPT_NAME = '/someuri'
Afterwards, you may still have problems with static files, the css, etc., even in the admin application. In the default config, these are served by the Django development server without changes. However, with the above changes the static files will be lost. Assuming you still want to serve these files through the internal Django development server (and not through an external web server) you need to add to the settings.py project file:
STATIC_SUFFIX = '/static/'
STATIC_URL = FORCE_SCRIPT_NAME + STATIC_SUFFIX
MEDIA_SUFFIX = '/media/'
MEDIA_URL = FORCE_SCRIPT_NAME + MEDIA_SUFFIX
In the same file, you also need to change TEMPLATES and add the following:
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ STATIC_ROOT ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
You will then want to gather the static files into the directory defined:
python manage.py collectstatic
or
python3 manage.py collectstatic
The project level urls.py file should look like this (Django v1.11):
import os
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from django.views.generic.base import TemplateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
] + static(settings.STATIC_SUFFIX, document_root=settings.STATIC_ROOT)
Thereafter, the admin package should work okay, with appropriate stylesheets and everything. The only thing that does not seem to work well is the "VIEW SITE" link since it misses a slash. I did not find a solution for that but probably it involves hacking the admin application.
Beyond that, there are various guides online for installing Django under a sub-path. It's messy but the above avoids the worst headaches.
This should work for you.
from django.conf.urls import patterns, url
urlpatterns = patterns('',
(r'^someuri/admin/', include(admin.site.urls) ),
)

Template Does not exist

I am new to Django. I use pydev eclipse as an IDE. First I created a project then an application welcome on that project. I made a folder named Templates within the project and make a file "home.html" and home.html contains
<div>
This is my first site
</div>
I modify the settings.py file as
TEMPLATE_DIRS = ("Templates")
INSTALLED_APPS = (
..........#all default items
'welcome', #the added one
)
views.py includes
from django.shortcuts import render_to_response
def home(request):
return render_to_response('home.html')
urls.py contains
from django.conf.urls import patterns, include, url
from welcome.views import home
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'MajorProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^home/$', home),
)
then I run it as django project and open my browser and see on localhost:8000/home
it shows error
TemplateDoesNotExist at /home/
home.html
Request Method: GET
Request URL: http://localhost:8000/home/
Django Version: 1.6
Exception Type: TemplateDoesNotExist
Exception Value:
home.html
Exception Location: C:\Python27\django\template\loader.py in find_template, line 131
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
Python Path:
['D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\MajorProject',
'C:\\Python27\\lib\\site-packages\\distribute-0.6.35-py2.7.egg',
'D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\MajorProject',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\wx-2.8-msw-unicode',
'C:\\Windows\\SYSTEM32\\python27.zip']
Server time: Sun, 2 Jun 2013 14:25:52 +0545
Try to set Templates Directory on setting.py.
as
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__),'templates'),
)
If you're using Django 1.8+
You'll get this warning:
(1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_DIRS, TEMPLATE_DEBUG.
Add your template directory to the Base TEMPLATES setting under the DIRS dictionary
Like so:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
root("templates"), #### Here ####
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
in Django 1.9
in settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR+r'\templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
...
],
},
},
]
Directory with templates should be named templates, not Templates (even though on windows it may be the same). Also make sure, you have application in PYTHONPATH or the correct directory structure of your project and application like:
project/
project/
settings.py
...
welcome/
templates/
home.html
views.py
...
manage.py
Then you don't need to change TEMPLATE_DIRS because app_directories.Loader (enabled by default) will find the templates in your application.
Also of if you still want to change TEMPLATE_DIRS, use absolute paths, but preferred way is the app_directories.Loader.
check below steps to fix
step 1:
Inside templates, 'DIRS' : [ ], metion this:
'DIRS': [os.path.join(BASE_DIR, 'templates')],
step 2:
Go in your views.py file and look for template_name (check its spelling and also check did you mentioned the right html file here or not)
step 3:
Check in your urls.py file wether you mentioned the right template name or not in the path
format: urlpatterns = [ path(" ", class name or function name, name = template name)
BASE_DIR = Path(file).resolve().parent.parent
This is default directory code by Django
And looks like this
C:\user\pc_name\django_project
But if you delete last .parent it will looks like this
C:\user\pc_name\django_project\django_project
So new BASE_DIR code which is this
BASE_DIR = Path(file).resolve().parent
Add this variable to TEMPLATE_DIR
TEMPLATE_DIR = os.path.join(BASE_DIR, 'template")
And last code define this
C:\user\pc_name\django_project\django_project\template
In the end safely uptade DIRS
'DIRS': 'TEMPLATE_DIR'
Hope you did