Override url.html in Django Admin - django

I have overridden the template url.html(template path: /admin/widgets/url.html) file of Django Admin. Now I need to keep that overridden file in my project folder so that whenever the functionality of url.html file is needed, the admin app should look into the overridden template(present inside the project folder) but not the template from Django Admin templates present inside the site-packages folder.
Here is my settings.py file settings for templates:
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
os.path.join(BASE_DIR, "company", "app2"),
os.path.join(BASE_DIR, "company", "app2", "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",
]
},
}
]
I have placed the overridden file in the following path in my project:
compnay -> app2 -> templates -> admin -> widgets -> url.html
url.html is present in the widgets folder. The changes made in the overridden template aren't being reflected in the Django Admin UI(For example, in the url.html file, I kept target="_blank" attribute inside the anchor tag to open the corresponding link in a new tab. These changes aren't being reflected.). So, I think it's not taking overridden template present inside my project.
What should I do to take the overridden url.html file present in my project folder?

I had same problem. Solution to problem is:
Add 'django.forms' to your INSTALLED_APPS
Add FORM_RENDERER = 'django.forms.renderers.TemplatesSetting' to
your settings.py
Documentation says:
This renderer gives you complete control of how form and widget templates are sourced.

Related

Whats the correct structure for Django templates?

I have a project in Django called: "my_site", and an app called "blog", I'm trying to render the "index.html" inside the path: my_site/blog/templates/blog/index.html. But keep getting this error:
Template-loader postmortem
Django tried loadi
ng these templates, in this order:
Using engine django:
django.template.loaders.filesystem.Loader: C:\Users\Ricardo Neto\Dev\Django_Projects\my_site\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Python310\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Python310\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\Ricardo Neto\Dev\Django_Projects\my_site\blog\templates\index.html (Source does not exist)
The view:
def index(request):
return render(request, 'index.html')
the urls.py:
urlpatterns = [
path('', views.index),
path('posts', views.show_all_posts),
path('posts/<slug:slug>', views.show_post)
]
If i move the index.html outside the blog folder, like in this example: my_site/blog/templates/index.html
the code runs and the index.html renders without problem, but i was taught that the correct structure is to create a folder inside templates with the same name of the app.
So could anyone please explain me the way i should structure my files?
rather than keeping it within the app. I prefer to keep it under the project file. my_site/templates/app_x/index.html
├───accounts
│
├───django_project
│
└───templates
├───accounts
└───registration
In settings.py file update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py.
import os
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',
],
},
},
]
If I open separate files under templates, I render them as folder_name/index.html, otherwise directly as index.html.
Django resolves templates relative to the "templates" directory located inside the app directory and chooses the first template across all apps whose name matches. For example, if you have two apps: blog and news both with templates named "index.html" in the "templates" directory, Django would not be able to choose correctly one of them. To make a distinction you can create a subfolder inside the "templates" directory named after the corresponding application: "blog/templates/blog/index.html" and "news/templates/news/index.html". And after that you can use those templates in the view functions like this: render(request, 'news/index.html') and render(request, 'blog/index.html').
You can read about this topic here, check the remark "Template namespacing": https://docs.djangoproject.com/en/4.0/intro/tutorial03/

Template in Django not found

In the code below, my problem is that template file 'UserAccount' is not found. I set the app in the settings and create a directory in the app and an html file in the directory.
from django.shortcuts import render
# Create your views here.
def login(request):
context = {}
return render(request, 'UserAccount/login.html', context)
this should be your settings.py:
INSTALLED_APPS = [
# django essentials
"django.contrib.admin",
...
# my apps
"myapp", #the app name is "myapp"
]
...
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [str(BASE_DIR.joinpath("template"))], # change this line in your settings
"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",
],
},
},
]
now create a directory in the same directory as your apps. sth like this:
myapp
app_two
template
...
now in template directory create another directory with the name of your app. in tha t put your html fiels. like this:
| myapp
| app_two
| template
|----myapp
|----sth.html
|----sth_2.html
|----app_two
now when you want to reference them do it like this:
return render(request, 'myapp/sth.html', context)
General tips on asking question on Stackoverflow:
for title : a summary of your problem with keywords like "django" or "django-views"
for putting your code use three backticks --> code
search a lot before asking question. there is a huge chance that someone had posted the same problem before you and you can find your answer there

Django Installed Apps - path full/partial

I was creating this django project and it has a class named "jobs". Now how do i add this "jobs" app in my setting.py. Some say we need to add full path like
INSTALLED_APPS = [
'jobs.apps.JobsConfig'
]
and some say just add the app name like
INSTALLED_APPS = [
'jobs'
]
can anyone tell me which is correct please?

Importing django.contrib.auth.urls does not play well with existing admin templates

I've been trying to follow documentation on using builtin Django templates to login/logout nonstaff users on a Django (1.9) site. In particular, I modified the urlconf by adding
url('^', include('django.contrib.auth.urls'))
which brings in /login and /logout endpoints and views with default template names preprogrammed.
The default template names for login and logout are registration/login.html and registration/logged_out.html. The first one doesn't exist anywhere, so I assumed I should create a templates/registration/ and create the login template, which I did. I thought the same thing should work for the logout, except it doesn't.
What actually happens is that the template resolves to django.contrib.admin.templates.registration.logged_out.html. This is pretty but stinks because the login link points to the admin login, which no nonstaff user will be able to use.
I really wish I could use the urlconf above, use the default template names, but write my own templates. Isn't this possible? The alternative seems to be repeating a bunch of stuff and that isn't very Pythonic.
I imagine it might involve modification of the TEMPLATES setting, or changing the orders of something else in the settings.
Whatever the solution is, I hope it does not interfere with the proper resolution of the admin templates (i.e. it would be bad if those started using my new templates.)
Requested details:
I created a login.html in (appname)/templates/registration/, and it works just fine when visiting the login url.
I created a logged_out.html in (appname)/templates/registration/ also, but discovered that when visiting the logout url, I got the admin site logged_out template (the one that says "Thanks for spending some quality time with the Web site today."
My templates setting:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'debug': True,
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
INSTALLED_APPS = (
'django.contrib.admin',
'app',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles'
)
Project structure (omitting what I guess is nonessential, and using some generic names.)
project/
app/
templates/
app/
registration/
login.html
logged_out.html
models.py
views.py
admin.py
gettingstarted/
static/
settings.py
urls.py
The structure may look a bit weird since it was adapted starting from the Heroku "Getting started with python" app.
Update
I finally struck upon the right search terms in the Django bug tracker and found that is a known issue. Disappointingly it's already three years old with no comment in the past two years. I guess I will just have to bite the bullet and define my own urls that use templates on a different path.
Django's template lookup is done top down by the order of INSTALLED_APPS. Meaning that if you want to override a template, the overriding template app should be listed above the overriden one in the admin.
In this case, project.app should be placed above django.contrib.admin so when creating /registration/logout.html it'll be loaded before the admin template.
In general, the recommended order of installed apps is: project -> 3rd party apps -> django builtins. It also affects static files finders.
Because of a bug in Django, overriding the registration/logged_out.html template overrides the admin "logged_out" template as well.
You can include the logout view specifically and specify a different "logged out" template or next_page (the view where it redirects after logout):
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),
url('^', include('django.contrib.auth.urls')),
]
This will redirect to / after logout. It can also be a named url.
Or to change the logged_out template location use:
url(r'^logout/$', auth_views.logout, {'template_name': 'logged_out.html'}, name='logout'),
And then create logged_out.html in project/app/templates/.
I would use the first option if you want to redirect the user back to the home page after logout, and the 2nd if you want to display a "logged out" message.

django-summernote image upload

I recently implemented django-summernote with my forms, which works well for text. However, I struggle to get exactly how image upload works. Does anyone have some input on how it is done?
Problem
When choosing an image from file with Summernote, the Insert Image button is deactivated (works fine for image links). I did not write a custom 'upload_to' function, but as I get it, this is already done in django-summernote.
Details
Installed django-summernote according to documentation.
Added summernote to urls and in INSTALLED_APPS
Added summernote to my form field
directions = forms.CharField(
widget=SummernoteInplaceWidget(attrs={'maxlength':'4000'}),
required=False,
)
Also added some config in SUMMERNOTE_CONFIG (settings.py)
SUMMERNOTE_CONFIG = {
'iframe': True,
'airMode': True,
'width': '100%',
'height': '300',
'toolbar': [
# ['style', ['style']],
['font', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']],
# ['fontname', ['fontname']],
['fontsize', ['fontsize']],
# ['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['height', ['height']],
['table', ['table']],
['insert', ['link', 'picture', 'video', 'hr']],
['view', ['fullscreen', 'codeview']],
['help', ['help']],
], }
Do I also have to write my own backend for attachments (images)? STATIC_URL and MEDIA_URL is defined in my settings.py, if that matters for this issue.
Update November 29th 2014:
When choosing an image, the following error is given in the console: "undefined is not a function", which is related to
imageInput.fileupload();
The "Insert Image" button is disabled.
As my project is in developing mode, I have DEBUG=True in my settings.
My urls look like:
urlpatterns += patterns('',
url(r'^summernote/', include('django_summernote.urls')),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and Media_root and Media_url are set to:
MEDIA_ROOT = path.join(path.dirname(__file__), 'media',)
MEDIA_URL = '/media/'
I use picture uploads outside django-summernote with these settings.
Feels like I am missing something, but can´t see what.
Thanks in advance.
django-summernote shipped with backend support for image uploading out of box. So you don't have to write your own backend for it. MEDIA_ROOT or MEDIA_URL settings may have wrong value for uploading - permission problem or not valid path.
Run django project with runserver and please check the browser console(inspect) and python console after trying to upload an image.
And also refer Need a minimal Django file upload example for handling files on django project.