I have my own HTML page "stat.html" which shows some graphs, this is hyperlinked from a custom index page that I made using this method answer3.
My current admin/custom_admin.html page looks like this
{% extends "admin/index.html" %}
{% block content %}
{{block.super}}
<div class="module">
<table style="width:100%">
<caption>
<a class="section">Statistics </a>
</caption>
<tbody>
<th scope="row">
Stats Page
</th>
</tbody>
</table>
</div>
{% endblock %}
The link /myapp/statpage is link to a static html page, it is showing two google charts in it, something like this
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Stats</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script type = "text/javascript" src =
"https://www.gstatic.com/charts/loader.js"> </script>
<script type = "text/javascript"> google.charts.load('current',
{packages: ['corechart']}); </script>
<script src="{% static "v_stats.js" %}"></script>
</head>
<body>
<div id="container" style="width:80%; height:35vw; margin:"auto";"></div>
<div id="container1" style="width:80%; height:35vw; margin:"auto";"></div>
</body>
</html>
How do I just inherit the Django admin header in this stat.html page and have my own title, some links to static js pages and some content in it?
from myproject.admin import admin_site
admin.site.site_header = 'My administration'
You may now wish to use this elsewhere in your site, by inserting it as context into your templates.
Related
I am trying to use django-views-breadcrumbs to add breadcrumbs to a site. I can get it to work with some views but I am getting an error with a particular listview. When I attempt to visit this listview page I see the error.
The error appears to be related to a need for the correct context. So far I have not been able to figure this out.
The error:
NoReverseMatch at /projects/project/1/notes/
Reverse for 'projectnotes_list' with no arguments not found. 1 pattern(s) tried: ['projects/project/(?P<pk>[0-9]+)/notes/\\Z']
Request Method: GET
Request URL: http://co1.localhost:8000/projects/project/1/notes/
Django Version: 3.1.14
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'projectnotes_list' with no arguments not found. 1 pattern(s) tried: ['projects/project/(?P<pk>[0-9]+)/notes/\\Z']
Exception Location: /Users/user/.local/share/virtualenvs/osite-wGphEfbP/lib/python3.9/site-packages/django/urls/resolvers.py, line 689, in _reverse_with_prefix
Python Executable: /Users/user/.local/share/virtualenvs/osite-wGphEfbP/bin/python
Python Version: 3.9.6
Python Path:
['/Users/user/Desktop/otools',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
'/Users/user/.local/share/virtualenvs/osite-wGphEfbP/lib/python3.9/site-packages']
Server time: Sun, 20 Feb 2022 15:52:17 +0000
The list view:
class ProjectNotesList(ListBreadcrumbMixin,ListView):
model = ProjectNotes
template_name = 'company_accounts/project_notes.html'
comments = ProjectNotes.comments
def related_project(self, **kwargs):
project = get_object_or_404(Project, id=self.kwargs.get('pk'))
notes = ProjectNotes.objects.all
return notes
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk'))
return context
commentscount = ProjectNotes.objects.annotate(num_comments=Count('comments'))
The urls.py
from django.urls import path, include
from .views import CompanyProjects, CompanyProjectsDetailView, TodoCreateView, ProjectNotesList, ProjectNotesCreateView, ProjectCreateView, ProjectNotesDetailView, CompanyCompletedProjects, CompanyPausedProjects, TodosList, ProjectTodosDetailView, ProjectDocumentsList, ProjectDocumentsCreateView, ProjectDocumentsDetailView
from . import views
app_name = 'company_project'
urlpatterns = [
path('', CompanyProjects.as_view(), name='project_list'),
path('completed_projects', CompanyCompletedProjects.as_view(), name='completed_projects'),
path('paused_projects', CompanyPausedProjects.as_view(), name='paused_projects'),
path('add_project/', ProjectCreateView.as_view(), name='add_project'),
path('project/<int:pk>/', CompanyProjectsDetailView.as_view(), name='project_detail'),
path('project/<int:pk>/todos/', TodosList.as_view(), name='project_todos'),
path('project/<int:project_pk>/todo/<int:pk>/', ProjectTodosDetailView.as_view(), name='project_todo_detail'),
path('project/<int:pk>/add_todo/', TodoCreateView.as_view(), name='add_todo'),
path('project/<int:pk>/add_project_note/', ProjectNotesCreateView.as_view(), name='add_project_note'),
path('project/<int:pk>/notes/', ProjectNotesList.as_view(), name='projectnotes_list'),
#path('note/<int:pk>/add_project_note_comment/', ProjectNotesCommentCreateView.as_view(),
# name='add_project_note_comment'),
path('project/<int:project_pk>/note/<int:pk>/', ProjectNotesDetailView.as_view(), name='project_note_detail'),
path('project/<int:pk>/documents/', ProjectDocumentsList.as_view(), name='project_documents'),
path('project/<int:pk>/add_project_document/', ProjectDocumentsCreateView.as_view(), name='add_project_document'),
path('project/<int:project_pk>/document/<int:pk>/', ProjectDocumentsDetailView.as_view(), name='project_document_detail'),
]
The base and page templates:
base
<!DOCTYPE html>
{% load static %}
{% load view_breadcrumbs %}
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}Site{% endblock title %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link type="text/x-scss" href="{% static 'bootstrap/scss/bootstrap.scss' %}" rel="stylesheet" media="screen">
<!-- Custom CSS -->
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/>
<link rel="shortcut icon" type="image/png" href="{% static 'core_images/OH_favicon.png' %}"/>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-VJRXH7YFXZ"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-VJRXH7YFXZ');
</script>
</head>
<body>
<wrapper class="d-flex flex-column">
{% include 'nav.html' %}
<main class="flex-fill">
<div class="row">
<div class="col-12">
<br />
{% block breadcrumbs %}
{% render_breadcrumbs 'view_breadcrumbs/bootstrap4.html' %}
{% endblock breadcrumbs %}
{% block messages %}{% endblock messages %}
</div>
</div>
{% block content %}
<h1>Hello</h1>
{% endblock content %}
</main>
{% include 'footer.html' %}
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</wrapper>
</body>
</html>
page
<!-- templates/company_accounts/project_notes.html -->
{% extends 'base.html' %}
{% block content %}
<div class="section-container container">
<div class="general-section-header">
<div class="header-add-new">
<a class="btn btn-success" href="{% url 'company_project:add_project_note' project.pk %}" role="button">Add Note</a>
</div>
<h1>Notes for {{ project }}</h1>
</div>
{% if project.notes.all %}
{% for note in project.notes.all %}
<div class ="projectnotes-entry">
<div class="col-sm-8">
<div class="row-sm-6">
<div class="card mb-2">
<div class="card-body">
<div class="card-title">{{ note.title }}</div>
<div class="card-text">{{ note.body | safe | truncatewords:"20"|linebreaks }}
<div>{{ note.comments.all.count }} comments</div>
read more</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<p>No notes have been have been added yet.</p>
{% endif %}
</div>
{% endblock content %}
There is a demo included with the breadcrumb app the provides some insight. However I have not been able to figure out how to add necessaryt context using code from the demo.
The demo code:
class TestListsView(ListBreadcrumbMixin, ListView):
model = TestModel
template_name = "demo/test-list.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
view_paths = []
for instance in self.object_list:
view_paths.append(
(
instance.name,
detail_instance_view_url(instance),
),
)
context["view_paths"] = view_paths
return context
I have a Django Webapp which has a few forms for adding data to the database.
Once this data has been added, I want to present this on a dashboard. So I have views that were written that add the logic for the data to be presented, but as far as i can work out you only map 1 view to a template otherwise the data won't be displayed on the template.
I think there is a way to pass the data as a context, but I can't get my head around how to write this for my view.
A really simple view i have to display events
def all_events(request):
event_list = Event.objects.all()
return render(request, 'pages/event_list.html',{'event_list': event_list})
I'm passing this to event_list which works fine. But if I % include % on the dashboard I get the HTML but not the data, which I now understand is right.
But being an absolute bigger with Django, I could really do with an example of the above which I can then apply to all my other views.
Thanks
HTML Template
{% extends 'partials/base.html' %}
{% load static %}
{% block head_title%}
<title> Dashboard </title>
{% endblock %}
{% block extra_css %}
<link rel="stylesheet" type="text/css" href="{% static 'libs/toastr/build/toastr.min.css' %}">
<!-- plugin css -->
<link href="{% static 'libs/admin-resources/jquery.vectormap/jquery-jvectormap-1.2.2.css' %}" rel="stylesheet" type="text/css" />
{% endblock %}
{% block content %}
<div class="main-content">
<div class="page-content">
<div class="container-fluid">
<!-- start page title -->
<div class="row">
<div class="col-12">
<div class="page-title-box d-sm-flex align-items-center justify-content-between">
<h1 class="display-4 mb-0">Dashboard</h1>
<div class="page-title-right">
<ol class="breadcrumb m-0">
<li class="breadcrumb-item">Dashboard</li>
<li class="breadcrumb-item active">Dashboard</li>
</ol>
</div>
</div>
</div>
</div>
</div>
{% include 'pages/event_list.html' %}
</div>
{% endblock %}
{% block extra_js %}
<script src="{% static 'libs/#ckeditor/ckeditor5-build-classic/build/ckeditor.js' %}"></script>
<!-- init js -->
<script src="{% static 'js/pages/form-editor.init.js' %}"></script>
<!-- pristine js -->
<script src="{% static 'libs/pristinejs/dist/pristine.min.js' %}"></script>
{% endblock %}
I'm not sure if I understand your problem correctly, but just including the pages.html file will not pass the correct context data to the dashboard if it is not in the view connected to the dashboard endpoint. Django directs an endpoint to a view, the view grabs the context data from the models or creates it, and returns a template with the data.
Your url pattern for the dashboard could look something like this
urlpatterns = [
path('dashboard/', dashboard_view, name="dashboard"),
]
and your view could then look like this
def dashboard_view(request):
event_list = Event.objects.all()
return render(request, 'path/to/dashboard.html',{'event_list': event_list})
Assuming the event_list.html file uses a context data variable correctly like the example shown below, it will be displayed on the dashboard as well.
{{ for event in event_list }}
{{ event.attribute }}
{{ endfor }}
What you're passing to the render() function is just a dictionary of context data for the templates to use, so as long as the correct data is in that dictionary and the correct variable names from the dictionary are used in the template being rendered, or any templates included within it, it should be displayed.
Hope this helps answer your question!
Sorry for my bad english.
I use
{% ishout.js %}
inside head to render scripts file in django template but they display as string
"<script type="text/javascript" src="http://localhost:5500/socket.io/socket.io.js"></script>
<script type="text/javascript" src="http://localhost:5500/client/ishout.client.js"></script>"
and inside body not inside head.
And other scripts after that are displayed in body too.
I searched and find out by encoding but i cannot find how to fix it.
UPDATE
This is views.py file
#login_required
def home(request):
users = User.objects.exclude(id=request.user.id)
v = RequestContext(request, {'users':users})
# return render(request, 'home.html', {'users':users})
return render_to_response('home.html', v)
This is home.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Home</title>
{% load drealtimetags %}
{% ishout_js %}
</head>
<body>
<h1>Dashboard</h1>
{% for user in users %}
{{ user.first_name }}Alert (Hello)
{% empty %}
<b>No user found</b>
{% endfor %}
</body>
</html>
UPDATE 2:
This is page source
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Home</title>
<script type="text/javascript" src="http://localhost:5500/socket.io/socket.io.js"></script>
<script type="text/javascript" src="http://localhost:5500/client/ishout.client.js"></script>
<script>
ishout.on('alertchannel', function(data){
alert(data.msg);
});
ishout.init();
</script>
</head>
<body>
<h1>Dashboard</h1>
phucAlert (Hello)
Alert (Hello)
</body>
</html>
And when I inspect
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
</head>
<body>
<script type="text/javascript" src="http://localhost:5500/socket.io/socket.io.js"></script>
<script type="text/javascript" src="http://localhost:5500/client/ishout.client.js"></script>
<script>
ishout.on('alertchannel', function(data){
alert(data.msg);
});
ishout.init();
</script>
<h1>Dashboard</h1>
phucAlert (Hello)
Alert (Hello)
</body>
Snapshot
It's because the tag is returning HTML that is getting escaped, so the browser is rendering it as text inside the body instead of as real HTML in the <head>.
Turn off autoescape around the tag:
{% autoescape off %}
{% ishout_js %}
{% endautoescape %}
Since you are including each of those js files, and you want it rendered and interpreted as html script tags, try making it a template file _ishout_includes.html instead. You don't need to change the contents of the file at all.
From there, use the {%include%} tag. It would look like
{% include _ishout_includes.html%}
I used Django to create a blog and i want to display a single post on page when i click on a post title and no matter of the used method i cannot display anything on the page.
My Views:
class One_Per_Page(DetailView):
model = AboutMe
objects = AboutMe(id)
def oneperpage(request):
entry = One_Per_Page.objects.get_queryset(pk=AboutMe.id)
#entries = super(One_Per_Page).get_queryset()
return render_to_response('blog/aboutme_detail.html', {'AboutMe': entry})
this is the URL i use:
url(r'^(?P<pk>\d+)$', One_Per_Page.as_view(), name='oneperpage
this is the html page that must display a single post when the title of it is cliked:
<!DOCTYPE html>
<html lang="en">
<head>
<title>EBA</title>
<meta charset="utf-8"/>
<link rel="stylesheet" href="/static/css/styles.css" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body class="body">
<header class="mainHead">
<img src="/static/img/mainlogo.png" %} width="700" height="144" %}>
<nav>
<ul>
<li><a href='/'>Home</a></li>
<li><a href='/blog/'>Blog</a></li>
<li><a href='{{ STATIC_URL }}/latestnews/'>News</a></li>
<li><a href='{{ STATIC_URL }}/archive/'>Archive</a></li>
</ul>
</nav>
</header>
{% block content %}
<div>
<article>
<h4>{{ entry.titleMe }}</h4>
<p class="postInfo">
on {{ entry.dateMe }}
</p>
<div class="typicalArticle">
{{ entry.contentMe|safe|linebreaks }}
</div>
</article>
</div>
{% endblock %}
<footer class="mainFooter">
<p> copyright © 2015</p>
</footer>
</body>
</html>
Can anyone help me to do this right?
I dont know what error you are getting but try this, actually you dont need to do much:
url(r'^stuff/(?P<pk>\d+)/', One_Per_Page.as_view(
template_name='detail.html'), name="detail")
and
class One_Per_Page(DetailView):
model = AboutMe
and in template, you have automatically object instance you can access like this:
{{ object.name }}
{{ object.biography }}
I have to web page using django.
In html, I assign external image link to img src tag.
but, 403 forbidden error and not show image.
when I paste image external link to browser address, the image show.
I think.. it is referer checking. so I use ReferrerKiller.js in Changing the http referer in javascript.
first image is shown. but other is not.
I check network using chrome developer tool.
other image canceled. I don't know that.
I want to listen any idea about this problem.. Referer checking and why show only first image? other not?
below home.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
{% load staticfiles %}
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript" src="{% static "js/ReferrerKiller.js" %}"></script>
<title>island</title>
</head>
<body>
<h1> nanpa </h1>
<br/>
{% for entrySummary in entrySummaryList %}
title :
{{ entrySummary.entry_title }}
{{ entrySummary.entry_pub_date }} <br/>
description : {{ entrySummary.entry_description }} <br/>
image : <span id="image_kill_referrer"></span>
<!-- <img src= ("{{ entrySummary.entry_representaion_img }}"/> -->
<script>
document.getElementById('image_kill_referrer').innerHTML = ReferrerKiller.imageHtml("{{
entrySummary.entry_representaion_img }}");
</script>
{% endfor %}
</body>
</html>
document.getElementById() returns only one item (the first item, because all images in you code have same id). Use another methods like document.getElementsByClassName.
Try following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
{% load staticfiles %}
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript" src="{% static "js/ReferrerKiller.js" %}"></script>
<title>island</title>
</head>
<body>
<h1> nanpa </h1>
<br/>
{% for entrySummary in entrySummaryList %}
title :
{{ entrySummary.entry_title }}
{{ entrySummary.entry_pub_date }} <br/>
description : {{ entrySummary.entry_description }} <br/>
image : <span class="image_kill_referrer"></span>
{% endfor %}
<script>
var i, images = document.getElementsByClassName('image_kill_referrer');
var urls = [
{% for entrySummary in entrySummaryList %}
"{{ entrySummary.entry_representaion_img }}",
{% endfor %}
"DUMMY"
];
for (i = 0; i < images.length; i++) {
images[i].innerHTML = ReferrerKiller.imageHtml(urls[i]);
}
</script>
</body>
</html>
Or, use different id for each image:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
{% load staticfiles %}
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript" src="{% static "js/ReferrerKiller.js" %}"></script>
<title>island</title>
</head>
<body>
<h1> nanpa </h1>
<br/>
{% for entrySummary in entrySummaryList %}
title :
{{ entrySummary.entry_title }}
{{ entrySummary.entry_pub_date }} <br/>
description : {{ entrySummary.entry_description }} <br/>
image : <span id="image_kill_referrer{{ forloop.counter }}"></span>
<script>
document.getElementById('image_kill_referrer{{ forloop.counter }}').innerHTML = ReferrerKiller.imageHtml("{{
entrySummary.entry_representaion_img }}");
</script>
{% endfor %}
</body>
</html>