Display multiple views in single page - django

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!

Related

leaflet does not display the map in my django application

I am developing an application with django. In a page of this application I want to display a map with leaflet. I try to display a basic map according to the information I could have on the leaflet site but nothing is displayed. There is not even an error message in the console.
templatefile.html:
{% extends 'elec_meter/base.html' %}
{% load static %}
{% block title %}Geolocalisation des compteurs - Interactiv {% endblock %}
{% block titre %} Carte {% endblock %}
{% block css %}
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.8.0/dist/leaflet.css"
integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.8.0/dist/leaflet.js"
integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ=="
crossorigin="">
</script>
<script src="{% static 'assets/js/main.js' %}"></script>
<style>
<link href="{% static 'assets/css/style.css' %}" rel="stylesheet" />
</style>
{% endblock %}
{% block add %}{% endblock %}
{% block content %}
<div class="row" onload="init">
<div id="mapid" style="height:450;">
</div>
</div>
{% endblock %}
Here is the content of my js file which initializes the map: main.js
function init(){
const coordGabon = {
lat: -0.803689,
lng: 11.609444
}
const zoomLevel = 13;
const mymap = L.map('mapid').setView([coordGabon.lat, coordGabon.lng],zoomLevel);
const mainLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 19,attribution: '© OpenStreetMap'}).addTo(mymap);
}
From reading your code, I suspect there are two things at play:
onload is not a valid event for a div element
height:450; is not valid CSS
In short: the map does not get instantiated and has no height.
Please try the following; modify this part
{% block content %}
<div class="row" onload="init">
<div id="mapid" style="height:450;">
</div>
</div>
{% endblock %}
to
{% block content %}
<div class="row">
<div id="mapid" style="height:450px;"></div>
</div>
<script>
// in case the document is already rendered
if (document.readyState !== 'loading') {
init();
}
// modern browsers
else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init());
}
</script>
{% endblock %}
Of course this is a quick prototype solution. If it works, I recommend moving the inline CSS style to the 'assets/css/style.css' file.

Jinja extends doesn't load image

I'm using Flask for a small web app and having trouble to get my background image to display after extending using Jinja.
My layout.html contains a header:
<!-- Header section -->
<header class="header-section">
<div class="header-warp">
<div class="container">
<a href="#" class="site-logo">
<img src="{{ url_for('static', filename='img/logo.png') }}" alt="">
</a>
<div class="user-panel">
{%if session.user_id %}
Logout
{% endif %}
</div>
<div class="nav-switch">
<i class="fa fa-bars"></i>
</div>
</div>
</div>
</header>
<!-- Header section end -->
<main>
{% block main %}
{% endblock %}
</main>
And in another html file, I want to extend the layout:
{% extends "layout.html" %}
{% block title %}
Register
{% endblock %}
{%block main%}
<section class="hero-section set-bg" data-setbg="{{ url_for('static', filename='img/review-bg.jpg') }}">
However, the review-bg.jpg doesn't load and instead, I received a blank section. However, when I straight up copying the layout (not using extends anymore), the image loaded correctly. I double checked with (http://127.0.0.1:5000/static/img/review-bg.jpg) and the path correctly return the image.
Anyone can help explain to me why Jinja doesn't load the image after extending?
The problem seems to be in data-setbg - it can be React script, look here:
html tag attribute "data-setbg" is not working in React project
Or try to google "data-setbg is not working"
Edit the extension to:
{% extends "layout.html" %}
{% block title %}
Register
{% endblock %}
{%block main%}
<img src="{{ url_for('static', filename='img/review-bg.jpg') }}" alt="">
Do you see the image now? If so (what I suspect), it's not jinja/flask related but something else is going on. If not, right click on the page in firefox and press view source. Where is the link pointing to?

Django extended template not displaying content

There have been a few other threads about this topic, but specifically one with an answer of a urls.py issue didn't resolve mine...
I'm attempting to extend a base template. I have two files, base.html and index.html. Base has basic navigational elements, CSS, etc., and index.html extends base. I'm pointing to index.html in my view, but all I can see is code from base.html -- the index.html code is not displaying. Any help is appreciated. Also, there are no errors reported anywhere for any of this code.
views.py:
class DashboardView(TemplateView):
context_object_name = 'home_list'
template_name = 'index.html'
queryset = Media.objects.all()
def get_context_data(self, **kwargs):
context = super(DashboardView, self).get_context_data(**kwargs)
context['jobs'] = Job.objects.all()
return context
Relevant portions of urls.py:
url(r'^admin/', include(admin.site.urls)),
url(r'^apiroot/', router.get_api_root_view()),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', dashboard_views.DashboardView.as_view(), name="home_list"),
base.html in the templates dir: (Note that the "Test." part of this does show up on the screen, but that is the last element on the page when loaded.)
{# load the tag library #}
{% load bootstrap3 %}
{% load staticfiles %}
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="{{STATIC_URL}}bootstrap3/css/bootstrap.min.css" rel="stylesheet">
{# load CSS and Javascript #}
{% bootstrap_css %}
{% bootstrap_javascript %}
{# Display django.contrib.messages as bootstrap alerts #}
{% bootstrap_messages %}
<div class = "container">
Backup Administraton (test)
</div>
<!------Navbar ---------->
<header class = "navbar navbar-inverse navbar-fixed-top" role = "banner">
<div class = "container">
<div class ="navbar-header">
<button type = "button" class= "navbar-toggle" data-toggle = "collapse" data-target = "#dropdown">
<span class = "sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
Backup Administration
</div><!-- End Navbar Header-->
<div class = "collapse navbar-collapse" id = "dropdown">
<ul class = "nav navbar-nav navbar-right" role = "navigation">
<li>Home</li>
<li>Reports</li>
<li>Snapshots</li>
<li>Restores</li>
</ul>
</div><!-- End Nav Contents -->
</div><!-- End Container -->
</header>
Test.
Contents of index.html:
{% extends "base.html" %}
<BR><BR><BR><BR>
Testing contents of index.html
{% block content %}
<BR><BR><BR><BR><BR>
This is index.html<BR>
{% endblock %}
The index.html contents (ie the "Testing contents") never displays on the screen. FWIW, the BR's were to make sure the text didn't display behind the black nav bar.
Thanks for your time.
You need to add a content block to your base.html, for example:
...
<div class = "container">
Backup Administraton (test)
</div>
<div class="container">
{% block content %}
{% endblock content %}
</div>
<!------Navbar ---------->
...

styling active element menu in flask

i have following templates structure in flask:
templates/
/posts
list.html
base.html
index.html
my base.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ITV</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}">
<!-- Latest compiled and minified JavaScript -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<body>
{%- block topbar -%}
<nav class="navbar navbar-default navbar-static-top" role="navigation">
<!-- We use the fluid option here to avoid overriding the fixed width of a normal container within the narrow content columns. -->
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/">САПР</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-8">
<ul class="nav navbar-nav">
<li class="active">Головна</li>
<li>Новини</li>
<li>Розклад занять</li>
</ul>
</div><!-- /.navbar-collapse -->
</div>
</nav>
{%- endblock -%}
<div class="container">
<div class="content">
{% block page_header %}{% endblock %}
{% block content %}{% endblock %}
</div>
</div>
</body>
</html>
i can render template, for example : render_template('posts/list.html'), which extends my base.html
my list.html:
{% extends "base.html" %}
{% block content %}
Posts
{% endblock %}
How can i set active element menu in base.html
<li class="active">Головна</li>
<li>Новини</li>
<li>Розклад занять</li>
when i'm rendering list.html, and cant pass data directly into base.html?
In Flask, the request variable is available by default in templates, so you can simply check request.path in your base.html and adjust your links.
<li {% if request.path == '/' %}class="active"{% endif %}>
Головна
</li>
Can use a ternary also...just a bit shorter & nicer
<li {{ 'class="active"' if request.path == '/' else '' }}>
Головна
</li>

django template extends not working

This is my base.html
<!DOCTYPE html>
<head>
<title> My Site </title>
</head>
<body>
<div id="wrapper">
<!-- HEADER START -->
{% block nav %} {% endblock %}
{% block index %} {% endblock %}
</div>
</body>
</html>
this is my nav.html
{% extends "base.html" %}
{% block nav %}
<div id="header">
<div class="inner">
<div class="nav">
<ul>
<li class="current">Home</li>
<li>About</li>
<li>Blog</li>
<li>Contact</li>
</ul>
</div>
<div class="clear"></div>
</div><!-- .inner end -->
</div><!-- #header end -->
<!-- HEADER END -->
{% endblock %}
this is my index.html
{% extends "base.html" %}
{% block index %}
<p> hello </p>
{% endblock %}
I have done it several times before before but i am clueless as to why this is NOT working?
the urls and views are here.
Well everything is fine, the trouble that you are having is that
you are confused, just naming a block in base does not calls it.
Mark the difference between extends and include.
You have counfused extends to include.
Once in your views if you call say index.html it will be rendered properly.
The effect you want can be achieved by changing the base.html in your views to index.html.
Hope this helps. more can be read here: https://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance
For more people who end up here (as myself), main thing to note is that when you use {% extends 'something.html' %}, you cannot use anything other than these template tags at the top-level.
You can obviously have html tags inside these tags (like block tags), but don't put ANYTHING outside the template tags.
Also helps if you change the path in extends, for example {% extends 'mysite/index.html' %}. And view function must render the file with extends, not the basic one.
In views.py, you have to call the template that extends the other template, not the other way around. In your example you should call nav.html.
try do this
{% extends 'appname/index.html' %}