Template changes are not appearing in Django admin site - python

I am going through the Django tutorial, step 2 found here: https://docs.djangoproject.com/en/1.7/intro/tutorial02/
I've followed the steps in the tutorial and here is my file structure:
mysite
----mysite
--------templates
------------admin
----------------base_site.html
--------settings.py
----polls
----manage.py
Here is the change I made in settings.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
#this is the change
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
Here are the contents of base_site.html:
{% extends "admin/base.html" %}
{% block title %}{{ title }} | {{ site_title|default:_('Polls site admin') }}{% endblock %}
{% block branding %}
<h1 id="site-name">{{ site_header|default:_('Polls administration') }}</h1>
{% endblock %}
{% block nav-global %}{% endblock %}
I don't understand what I'm doing wrong. None of the changes show up in the admin site. I've restarted it several times. It still shows the default "Django administration" etc. I've even tried clearing my browser cache.
Edit: I also tried it in a different browser just to double check and the changes still do not appear.
Help!

Your templates directory is one level below where you're telling Django to look.
Either change it to:
PROJECT_DIR = os.path.dirname(__file__)
BASE_DIR = os.path.dirname(PROJECT_DIR)
#this is the change
TEMPLATE_DIRS = [os.path.join(PROJECT_DIR, 'templates')]
Or change it to:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
#this is the change
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'mysite', 'templates')]

Related

Django failing to load images from my media file but is not giving me a 404 error and has the correct file path. What could be causing this issue?

To clarify my title, I have a database set up in my Django application that takes information from albums, including album covers. The image saves in the database, goes to the correct MEDIA_ROOT specified in my settings.py file, and shows the correct url path when checking the request path. I am using the latest version of Django and have Pillow installed to add the images into the database through the admin site.
Previously, when the file path was wrong, Django served a 404 error and couldn't find the file. Now that the path is correct, it loads for a moment and then says "server not found". When I inspect the image, it says that the "connection used to fetch this resource was not secure." however I am running the server locally and am not in a production enviroment, and all answers related to this issue seem to come from running the server in production.
When I attempt to open the image in a new tab, the tab says "Server not found" after attempting to load the filepath: "http://albums/filename_oja97pG.png" (you can see here the unsercure http response. I replaced the file name for privacy reasons.)
I am unsure what would be causing this issue. Here is my code:
models.py
class Album(models.Model):
title = models.CharField(
max_length=200,
validators=[MinLengthValidator(2, "Must be at least two characters.")]
)
release_date = models.DateField()
picture = models.ImageField(upload_to='albums/', blank=True)
content_type = models.CharField(max_length=256, blank=True, help_text='The MIMEType of the file')
description = models.TextField(blank=True)
def __str__(self):
return self.title
settings.py
BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
urls.py
urlpatterns = [
path('', views.MusicView.as_view(), name='music'),
path('albums/<int:album_id>', views.AlbumView.as_view(), name='album_detail'),
]
projects urls.py
...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
class AlbumView(DetailView):
model = Album
template_name = 'music/album_detail.html'
def get(self, request, album_id):
al = Album.objects.get(pk=album_id)
if al is not None:
context = {
'album' : al,
}
return render(request, self.template_name, context)
else:
raise Http404('Album does not exist.')
html template being served
{% extends 'base.html' %}
{% block welcome %}
{{ album.title }}
{% if album.content_type %}
<img src="/{{ BASE_DIR }}/{{ album.picture }}">
{% endif %}
{% endblock %}
Thanks for the help. Let me know what other information I can provide. I have attempted to load in other borwsers and have gotten the same problem.
You can try to use the url directly from the ImageFile field, so in your template:
{% extends 'base.html' %}
{% block welcome %}
{{ album.title }}
{% if album.content_type %}
<img src="{{ album.picture.url }}">
{% endif %}
{% endblock %}

adding custom CSS to django admin forms

I'm trying to style a form in django admin. I created a file to extend the base admin page with myApp/templates/admin/base_site.html and I'm calling in a new css file with:
{% extends 'admin/base.html' %}
{% load static %}
{% block branding %}
{% block extrastyle %}
<link rel='stylesheet' href='{% static 'css/admin.css' %}'>
{% endblock %}
{% endblock %}
I added a static directory and file at myApp/static/admin/css/admin.css. Since the admin app has already took control of URIs like http://127.0.0.1:8000/static/admin/css/base.css my app can't find static/css/base.css because it expects my admin.css to be in venv/lib/python3.9/site-packages/django/contrib/admin/static/admin/css. I want to extend the base css (add to it), not necessarily completely override it.
I'm guessing the answer is to edit settings.py to tell it to look at myApp/static but I'm not sure how. The relevant settings.py lines are:
STATICFILES_DIRS = [
os.path.join(PROJECT_DIR, 'static/'),
]
STATIC_URL = 'static/'
Thanks.

django: how do I actually override admin site template

I know this is asked and answered several times but I basically went over all the post on stack overflow and still couldn't get this to work. Right now I am just trying simply change the admin site title. I have the following:
#base_site.html
{% extends "admin/base_site.html" %}
{% block title %}{{ title }} | {{ site_title|default:_('NEW TITLE') }}{% endblock %}
{% block branding %}
<h1 id="site-name">{{ site_header|default:_('NEW TITLE') }}</h1>
{% endblock %}
{% block nav-global %}{% endblock %}
And I tried to put this in
my_site/templates/admin/base_site.html,
my_site/templates/admin/my_app/base_site.html, and
my_site/my_app/templates/admin/base_site.html,
but none of these work.
settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
],
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
},
},
]
I also tried just directly changing django\contrib\admin\templates\admin\base_site.html but still nothing happens.
I am really frustrated now and definitely could use some help, thanks
Updates:
Actually I found out that the local template does have effect.
Like here, the topmost white bar displays "#base_site.html!!##" which is what I put in my_site/templates/admin/base_site.html as a comment by chance. So it kinda working, but I still don't understand why I can't change the site title.
Add your Django app above 'django.contrib.admin' in settings -> INSTALLED_APPS. The order of apps in INSTALLED_APPS matters.
# settings.py
...
INSTALLED_APPS = [
"your_app.yourAppConfig", # add your app here
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
...
use my_site/my_app/templates/admin/base_site.html
put your app where you define this template before
'django.contrib.admin', in INSTALLED_APPS
source link
First open your settings.py and add a template folder:
TEMPLATES = [
{
'DIRS': [
'/path/to/your/django-project/templates', # Absolute Path
# os.path.join(BASE_DIR, 'templates') # Relative Path
],
...
Then move the file base_site.html to the following directory.
It's important to keep the structure on the file system.
/path/to/your/django-project/templates/admin/base_site.html
Content of base_site.html:
{% extends "admin/base_site.html" %}
{% block title %}{{ title }} | {{ site_title|default:_('NEW TITLE') }}{% endblock %}
{% block branding %}
<h1 id="site-name">Your new Title</h1>
{% endblock %}
{% block nav-global %}{% endblock %}
Django Documentation - Overriding Admin Site
Hope that helps.
So you should delete including the curly braces, and just write the text you want.
Remove: `{{ site_title|default:_('NEW TITLE') }}` Write: NEW TITLE
Remove: `{{ site_header|default:_('NEW TITLE' }}` Write: NEW TITLE
Also be sure that you placed the folders (templates/admin) in the root directory of your project. root directory is the container for all your app folders and also the manage.py file.
In other words, "templates" folder you want to create should be at the same level with manage.py file.
Your folder structure should look like this:
mysite/
templates/
admin/
base_site.html
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
...
...
I am not sure if I understand right. but you can easy to change the title by doing this:
in the "urls.py" file
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
.......
]
admin.site.site_header = 'My New Title'
admin.site.site_title = 'My New Title'
Then it should get the job done for you.
To change Django Admin site title, you can add these two lines in the admin.py of your Django app:
from django.contrib import admin
# change Django admin title
admin.site.site_title = 'My Blog Admin'
# change Django admin site header
admin.site.site_header = 'My Blog Admin'

Django can't show images on page

I'm desperatly trying to load some images to and from my database with the help of Django.
Loading seems to work, but getting them back from the database and showing them on a webpage doesn't seem to work.
Here some info:
Environment:
myproject
|_forpix(my app)
|_myproject
|_media
|_images
|_mimicry3.png
I have a base.html wich includes a contentblock "allimages.html":
{% extends "base.html" %}
{% block content %}
<div id="imagelist">
{% for image in images %}
<p><img src="{{MEDIA_ROOT}}{{image.picture.url}}" />{{ image }}</p>
{% endfor %}
</div>
{% endblock %}
This gives me the following result:
And if I click on one of the images i get:
In my settings.py I've set the following:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates/'),)
Now i really don't know how to fix this.
Can anybody provide me with some help (not the django tutorial, I've been there, tried that)
Do I have to add something in the urls.py especially for the media file? Or is it something else?
If i need to provide extra info, just ask.
^media/$ is a very wrong regex for media files. You should delete the $ (end-of-the-string) sign from this regex.
Usually for development environments I use this snippet in the urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Also remove the useless {{ MEDIA_ROOT }} part from your template code. It should be:
<img src="{{ image.picture.url }}" />
In adition the line that you have to add is..
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
But it has to be in the urls.py of your project folder. not in the urls.py of your App folder. I knew it by mistake.

django - static files in base template

How to make base template use static files and to make other templates that inherits base template to use same static files?
As I read in django documentation it writes about how to use static files that are used for specific app. But I can't seem to find a way to make it use static files from outside app.
Given app inherits everything, but static files.
My settings.py:
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'south',
'myproject.apps.finance',
'myproject.apps.base',
'django.contrib.admin',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
)
This is my current homepage settings:
url for homepage:
from django.conf.urls import patterns, include, url
from myproject.views import hello
urlpatterns = patterns('',
('', hello),
)
view of homepage:
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponse
import datetime
def hello(request):
hello = "Hello World"
return render_to_response('home/home.html', {'hello': hello})
homepage template:
{% extends "base/base.html" %}
{% block title %} My Homepage {% endblock %}
{% block content %}
<p>I say {{ hello }}</p>
{% endblock %}
base template:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<link rel="stylesheet" href="{{ STATIC_URL }}/css/style.css">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My Personal Finance Site</h1>
{% block content %}{% endblock %}
{% block footer %}
<section class="divider1">
<p>Thanks for visiting my site.</p>
<p>All rights reserved</p>
</section>
{% endblock %}
</body>
</html>
my CSS file is located in empty project called base. But I think there could be better way to use static files that are outside given app.
So what would be the best way to link base template with css file to make other templates that intherits base, to get same css file configuration?
base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
{% block css %}
<link rel="stylesheet" href="{{ STATIC_URL }}/css/style.css">
{% endblock %}
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My Personal Finance Site</h1>
{% block content %}{% endblock %}
{% block footer %}
<section class="divider1">
<p>Thanks for visiting my site.</p>
<p>All rights reserved</p>
</section>
{% endblock %}
</body>
</html>
page.html
{% extends "base/base.html" %}
{% block title %} My Homepage {% endblock %}
{% block css %}{{block.super}}
//put css here
{% endblock %}
{% block content %}
<p>I say {{ hello }}</p>
{% endblock %}
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from project_name import settings
admin.autodiscover()
urlpatterns = patterns('',
.......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
settings.py
import os
import sys
..........................
SITE_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(SITE_ROOT, 'app_name'))
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(SITE_ROOT, 'staticfiles'),
)
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(SITE_ROOT, 'templates'),
)
....................
make sure that the template tag "{% load static %}" is at the top of your .html file. that will load your static folder.
sample
{% load static %}
{% extends "base/base.html" %}
{% block title %} My Homepage {% endblock %}
{% block css %}{{block.super}}
//put css here
{% endblock %}
{% block content %}
<p>I say {{ hello }}</p>
{% endblock %}

Categories