I am working through some beginner Django tutorials to build a basic polling website. I have everything working, but I can't get the formatting to display properly on my "results" page for the polls.
How my page looks:
https://i.stack.imgur.com/AuB6q.png
The votes are being displayed, but you can't see them due to the formatting:
https://i.stack.imgur.com/QgMgr.png
How it is supposed to look:
https://i.stack.imgur.com/PmCOb.png
Below is my code on my results.html:
{% extends 'base.html' %}
{% block content %}
<h1 class="mb-5 text-center">{{ question.question_text }}</h1>
<ul class="list-group mb-5">
{% for choice in question.choice_set.all %}
<li class="list-group-item">
{{ choice.choice_text }} <span class="badge badge-success float-right">{{ choice.votes }} vote{{ choice.votes | pluralize }}</span>
</li>
{% endfor %}
</ul>
<a class="btn btn-secondary" href="{% url 'polls:index' %}">Back To Polls</a>
<a class="btn btn-dark" href="{% url 'polls:detail' question.id %}">Vote again?</a>
{% endblock %}
Any ideas on what I have wrong?
The problem is in your CDN. Change this CDN
<link href="cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/…" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
to this
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
Related
I get the following error when I try to run my app.
File "/Users/ccc/microblog/app/templates/errors/500.html", line 1, in top-level template code
{% extends "base.html" %}
File "/Users/ccc/microblog/app/templates/base.html", line 48, in top-level template code
{% block scripts %}
File "/Users/ccc/microblog/app/templates/base.html", line 49, in block "scripts"
{{ super() }}
jinja2.exceptions.UndefinedError: there is no parent block called 'scripts'.
I am following Miguel's Flask lessons and it seems like our code is largely similar. Hence I am not too sure this error appears.
This does not happen when I remove {{super()}} from the block script. The code runs smoothly then.
Here is my code for the base.html:
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
{% block navbar %}
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="{{ url_for('main.index') }}">Microblog</a>
</div>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li><a class="nav-link" href="{{ url_for('main.index') }}">Home</a></li>
<li><a class="nav-link" href="{{ url_for('main.explore') }}">Explore</a></li>
<li><a class="nav-link" href="{{ url_for('main.add_habit') }}">Habits</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
{% if current_user.is_anonymous %}
<li><a class="nav-link" href="{{ url_for('auth.login') }}">Login</a></li>
{% else %}
<li><a class="nav-link" href="{{ url_for('main.user', username=current_user.username) }}">Profile</a></li>
<li><a class="nav-link" href="{{ url_for('auth.logout') }}">Logout</a></li>
{% endif %}
</ul>
</div>
</div>
<hr>
</nav>
{% endblock %}
{% block content %}
<div class="container">
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-secondary" role="alert">{{ message }}</div>
{% endfor %}
{% endif %}
{% endwith %}
{# application content needs to be provided in the app_content block #}
<br>
{% block app_content %}{% endblock %}
</div>
{% endblock %}
{% block scripts %}
{{ super() }}
{{ moment.include_jquery() }}
{{ moment.include_moment() }}
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" 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.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
{% endblock %}
</body>
The error message said it right: you cannot use super() in your base.html template since it does not have a parent template. super() can be used only in a child template. When you put {{ super() }} into a block in a child template it will include the block's content from the parent template. E.g. if you want to add an additional script in the child.html you can write:
{% extends "base.html" %}
{% block scripts %}
{{ super() }}
<script src="https://cnd.com/path.to.script.js></script>
{% endblock %}
Now it will include all scripts from the parent and this one as well.
I am having trouble getting my search form to work in Django. When I search anything in the search bar I have set, I get an html page that just has the words Search on it. It's not the html page I set, though. My search template is in my projects templates directory. I am trying to search through my blog posts, and have attached my views and urls code.
This portion of my base template is within a navbar I grabbed from a sample Bootstrap blog template. This is the sample template. I've changed some things within my form.
base.html
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet" type='text/css'>
{% load static %}
<!-- Navbar here -->
<nav class="navbar navbar-expand-lg navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="{% url 'index' %}">ChairBlog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link {% if request.resolver_match.view_name == 'index' %}active{% endif %}" href="{% url 'index' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link {% if request.resolver_match.view_name == 'project_index' %}active{% endif %}" href="{% url 'project_index' %}">Projects </a>
</li>
<li class="nav-item">
<a class="nav-link {% if request.resolver_match.view_name == 'blog_index' %}active{% endif %}" href="{% url 'blog_index' %}">Blog </a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0" action="{% url 'search' %}" method="GET">
<input class="form-control mr-sm-2" type="search" name="q" placeholder="Search blog posts...">
<button class="btn my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<!-- Jumbotron stuff here -->
<div class="jumbotron d-flex align-items-center" style="margin-top: 56px;">
<div class="container text-center">
{% block jumbo_content %}
{% endblock %}
</div>
</div>
<!-- Main content goes here -->
<div class="container" style="padding-bottom: 200px;">
{% block page_content %}{% endblock %}
</div>
<!-- Footere here -->
<footer style="position: relative;">
<div class= "page-footer bg-dark" style="padding-top: 20px; margin-top: 50px;">
<div class="container" style="display: flex; justify-content: center;">
<div class= "row">
<div class="mb-10 flex-center">
<a class="github" href="https://github.com/ChairMane"><i class="fa fa-github-square fa-2x"></i></a>
</div>
</div>
</div>
<div class="footer-copyright text-center py-3" style="color: white;">Chair Birds Co.</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
Nothing within my blocks shows up when I view it. The tags <p>TEST</p> and <p>Is this working?</p> are not showing up. Neither is the block for the jumbo_content. I have set those correctly in my base.html, because they work with my other pages. It's just the search page it doesn't work on.
search.html
{% extends "base.html" %}
{% load static %}
{% block jumbo_content %}
<h1 class="display-4">Search Results</h1>
{% endblock %}
{% block page_content %}
<p>TEST</p>
{% if query %}
{% if results %}
<ul>
{% for post in results %}
<p>Is this working?</p>
<li>
{{ post.title }}, {{ post.body }}
</li>
{% endfor %}
</ul>
{% else %}
<p>Query returned no results.</p>
{% endif %}
{% endif %}
{% endblock %}
app/views.py
...
def search_posts(request):
query = request.GET.get('q', '')
if query:
queryset = (Q(title__icontains=query) | Q(body__icontains=query))
results = Post.objects.filter(queryset).distinct()
else:
results = []
context = {
'results' : results,
'query' : query
}
return render(request, 'search.html', context)
...
app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.blog_index, name='blog_index'),
path('<int:pk>/', views.blog_detail, name='blog_detail'),
path('<category>/', views.blog_category, name='blog_category'),
path('search/', views.search_posts, name='search'),
]
Here is how the search template is being viewed, I believe. My issues are as shown in the image. The inspector shows nothing within the blocks I've set. I have jumbo_content and page_content, and yet none of what I set within each block shows up.
Can anyone see anything immediately wrong here? I've tried this tutorial as well, and the same thing happens.
EDIT It seems my search_posts(request) function in my views is not even being called when I search something in the search bar. I tried tracebacks, and printing and nothing showed up in my terminal. Am I not correctly calling search_posts(request)?
I finally got my answer. I looked at this post and decided to try something. Apparently, if I change my app/urls.py line from this:
path('search/', views.search_posts, name='search'),
to this:
path('search', views.search_posts, name='search'),
then my whole view works.
Can anyone explain why that is? I had no idea removing a / could help.
Application - Flask app hosted on google app engine.
I get the following error when I try rendering my template
File "Show_Messages.html", line 1, in top-level template code
{% extends "AdminMaster.html" %}
TypeError: 'Key' object is not iterable
My template (Show_messages.html)
{% extends "AdminMaster.html" %}
{% block title %}News{% endblock %}
{% block page %}News{% endblock %}
{% block head %}
{{ super() }}
{% endblock %}
{% block content %}
<div class="container">
<div class="page-header">
<h1>News</h1>
</div>
<div class="col-lg-12">
<ul class="list-group">
{% for newsitem in newsitems %}
<li class="list-group-item">
<span class="badge">
<a href="Edit-NewsItem?ID={{ newsitem.key.urlsafe() }}">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</a>
</span>
</li>
{% endfor %}
</ul>
</div>
</div>
{% endblock %}
The route function
#message_admin_routes.route('/xxxx/xxxx-xxxx')
#authenticate_admin
def show_messages():
breadcrumb, user = build_user_and_breadcrumbs()
messages = MessageFactory().get_messages_key()
return render_template('Show_Messages.html',
user=user,
breadcrumb=breadcrumb,
newsitems=messages)
------Edited---------
AdminMaster.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<!--googleoff: snippet-->
{% block head %}
<title>CFC Melbourne - {% block title %}{%endblock%}</title>
<meta name="Section" content="{% block page %}{%endblock%}">
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<meta charset="UTF-8">
<link rel="stylesheet" href="https://storage.googleapis.com/xxxx/xxx/xxx.css" type="text/css">
<link rel="stylesheet" href="https://storage.googleapis.com/xxxx/xxxx/xxxx.css" type="text/css">
<link rel="shortcut icon" href="https://storage.googleapis.com/xxxx/xxxx/favicon.ico">
<link href='https://storage.googleapis.com/xxx/xxx.css' rel='stylesheet' type='text/css'>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
{% endblock %}
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
/**
* Function that tracks a click on an outbound link in Google Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label.
*/
var trackOutboundLink = function(url) {
ga('send', 'event', 'outbound', 'click', url, {'hitCallback':
function () {
document.location = url;
}
});
}
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'xxx-xx-xx', 'xxx-xx-xx.xxx.xxx');
ga('send', 'pageview');
</script>
</head>
<body itemscope itemtype="http://schema.org/WebPage">
<div id="wrap">
<div id="menu">
<nav class="navbar navbar-default" style="margin-bottom: 0px;">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/Eden"><div class='logo-text-a' style="color: black">CFC Melbourne Admin</div></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="dropdown">
Applications <span class="caret"></span>
<ul class="dropdown-menu">
<li>List all applications</li>
<li>Create new application</li>
<li>Something else here</li>
<li role="separator" class="divider"></li>
<li>Vision</li>
<li role="separator" class="divider"></li>
<li>One more separated linkkk</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
{{ user.nickname() }}<span class="caret"></span>
<ul class="dropdown-menu">
<li>Permissions</li>
<li>User Information</li>
<li role="separator" class="divider"></li>
<li>Logout</li>
</ul>
</li>
</ul>
</div><!-- /.navbar-collapse -->
</div>
</nav>
{% include 'AdminBreadcrumb.html' %}
</div>
<div id="content">
{% block content %}{% endblock %}
</div>
</div>
<!--googleoff: snippet-->
{% block footer %}
<script src="https://storage.googleapis.com/xxxx/js/jquery-2.1.0.min.js"></script>
<script src="https://storage.googleapis.com/xxxx/js/bootstrap.min.js"></script>
<script>
// Remove active for all items.
$('.page-sidebar-menu li').removeClass('active');
// highlight submenu item
$('li a[href="' + this.location.pathname + '"]').parent().addClass('active');
// Highlight parent menu item.
$('ul a[href="' + this.location.pathname + '"]').parents('li').addClass('active');
</script>
{% endblock%}
</body>
</html>
In your template code you have a for loop, which is expecting a iterable object like list. but some of your items passed here is non iterable.
you need to check the item is iterable before looping. An example given below;
<ul class="sitemap">
{%- for item in sitemap recursive %}
<li>{{ item.title }}
{%- if item.children -%}
<ul class="submenu">{{ loop(item.children) }}</ul>
{%- endif %}</li>
{%- endfor %}
</ul>
More details can be found here: https://stackoverflow.com/a/21006895/2336603
I have a form wherein I'm trying to insert a static image file in between an if-else loop in HTML. Here's the source code of the template:
<!DOCTYPE html>
<html>
<head>
<title>Rango</title>
</head>
<body>
<p>
<ul>
{% if user and not user.is_anonymous %}
<li>
<a>Hello {{ user.get_full_name|default:user.username }}!</a>
</li>
<li>
Logout
</li>
{% else %}
<li>
<img src="{% static "images/twitter.png" %}" />
</li>
{% endif %}
</ul>
</p>
<form id="evangelized_form" method="post" action="/rango/fillform/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
<b>{{ field.help_text }}</b><br>
{{ field }}<br><br>
{% endfor %}
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
However, this is the error that I'm encountering:
TemplateSyntaxError at /rango/fillform/
Invalid block tag: 'static', expected 'endif'
How are static images inserted in between if-else loop in templates in Django?
I believe you need to add
{% load staticfiles %}
at the top of your template.
I'm using django-pygments and am trying to us it like so (base.html)
<!DOCTYPE html>
{% load pygmentify %}
<head>
<link rel="stylesheet" media="screen" href="{% static 'django_pygments/css/pygments_default.css' %}" type="text/css">
</head>
<div class="row">
<div id="mainbody" class="small-12 large-8 large-offset-2 columns">
<body>
{% pygment %}
{% block content %}
{% endblock %}
{% endpygment %}
</body>
</div>
<div id="sidebar" class="small-12 large-2 columns">
</div>
<div class="small-12 large-8 large-offset-2 columns">
{% block comments %}
{% endblock %}
</div>
<div class="small-12 large-2 columns">
</div>
</div>
Then I'm passing {{ post.content|safe }} into block content. The pigmented code comes out as such:
I've tried changing the <ol> tags in the source code to <ul> but obviously that wasn't the issue. I also turned passed linenos=False and True but that only made it more weird as the line numbers aren't lined put correctly.
Anyone know what I might be doing wrong?
Apparently there was a problem with my css style sheet. I tried changing it and now it looks normal.