Jinja - If statement not work - Please help me [duplicate] - python

This question already has answers here:
Flask view return error "View function did not return a response"
(3 answers)
Closed 1 year ago.
I hope you can help me, because I can't find an solution on google.
Sense:
If you have logged in, you can switch to the settings otherwise not.
This is my code:
{% if settings is true %}
<a href="{{ url_for('main.settings') }}" class="navbar-item">
Settings
</a>
{% endif %}
This is the Full Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blog</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css" />
<link rel="stylesheet" href="/css/style.css" />
</head>
<body>
<section class="hero is-fullheight" style="background-color:#C4FCEF;">
<div class="hero-head">
<nav class="navbar">
<div class="container">
<div id="navbarMenuHeroA" class="navbar-menu">
<div class="navbar-end">
<a href="{{ url_for('main.index') }}" class="navbar-item">
Home
</a>
{% if current_user.is_authenticated %}
<a href="{{ url_for('main.profile') }}" class="navbar-item">
Profile
</a>
{% endif %}
{% if settings == true %}
<a href="{{ url_for('main.settings') }}" class="navbar-item">
Settings
</a>
{% endif %}
{% if not current_user.is_authenticated %}
<a href="{{ url_for('auth.login') }}" class="navbar-item">
Login
</a>
<a href="{{ url_for('auth.signup') }}" class="navbar-item">
Sign Up
</a>
{% endif %}
{% if current_user.is_authenticated %}
<a href="{{ url_for('auth.logout') }}" class="navbar-item">
Logout
</a>
{% endif %}
</div>
</div>
</div>
</nav>
</div>
<div class="hero-body">
<div class="container has-text-centered">
{% block content %}{% endblock %}
</div>
</div>
</section>
</body>
</html>
This is the Error:
TypeError:
The view function did not return a valid response.
The function either returned None or ended without a return statement.

Try changing {% if settings is true %} to {% if settings %} or {% if settings == true %} or {% if settings is sameas true %}
Refer here

Related

Flask Jinja2 not rendering bootstrap carousel

I'm wanting to render bootstrap carousel and other nested html elements. im newer to Jinja2 and didn't see anything on the internet talking about this particular issue.
here is my python
#app.route("/")
def index():
r = requests.get(os.environ['AWS_Product_URL'])
prods = list(json.loads(r.text))
return render_template("index.html", my_products=prods)
this works
{% for key in my_products %}
<p><strong>{{ key["name"] }}</strong><span>{{ key["price"] }}</span></p>
{% endfor %}
but this doesn't
{% for key in my_products %}
<div class="carousel-item">
<p><strong>{{ key["name"] }}</strong><span>{{ key["price"] }}</span></p>
</div>
{% endfor %}
I took an existing template and trying to make this dynamic. the class exists. I'm confused why Jinja2 is having trouble with a nested item in html.
Why??
You're probably just missing to add class active to the carousel item
bootstrap carousel items requires at least one active element, all the others will be hidden.
so try out adding something like
{% for key in my_products %}
<div class="carousel-item {% if loop.index == 1 %}active{% endif %}">
<p><strong>{{ key["name"] }}</strong><span>{{ key["price"] }}</span></p>
</div>
{% endfor %}
Just in case, here's template that I've tested with and it should be working fine assuming my_products is not empty.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col">
<div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner text-center">
{% for key in my_products %}
<div class="carousel-item {% if loop.index == 1 %}active{% endif %}">
<p><strong>{{ key["name"] }}</strong><span>{{ key["price"] }}</span></p>
</div>
{% endfor %}
</div>
<button class="carousel-control-prev bg-dark" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next bg-dark" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>

Hi, I have a problem with a django app. I want do make personalized pages for users with this url: url/user/id. But something doesn't work

I'm quite new in the programming world and that's my firs real project. Usually I solve my problems just sitting and thinking till my brain burns. But this time I'm really stacked. Maybe is easy but I really didn't find solutions
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('profilo/<int:my_id>/', views.profilo, name='profilo')
]
views.py
def profilo(request, my_id):
users = User.objects.get(id=my_id)
contex = {
"user": users
}
return render(request, 'profilo/profilo.html', contex)
base.html
{% load static %}
<html>
<head>
<title>Django Boyz blog</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="{% static 'css/blog.css' %}">
</head>
<body>
<div class="page-header">
{% if user.is_authenticated %}
<span class="glyphicon glyphicon-plus"></span>
<p class="top-menu">Ciao {{ user.username }} <small>(Log out)</small></p>
<span class="glyphicon glyphicon-user"></span>
{% if user.is_superuser %}
<span class="glyphicon glyphicon-inbox"></span>
{% endif %}
{% else %}
<span class="glyphicon glyphicon-lock"></span>
{% endif %}
<h1>Django Boyz Blog</h1>
</div>
<div class="content container">
<div class="row">
<div class="col-md-8">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
The error is this: NoReverseMatch at /
Reverse for 'profilo' with arguments '('',)' not found. 1 pattern(s) tried: ['profilo/(?P<my_id>[0-9]+)/$']
Thanks
In this line:
<span class="glyphicon glyphicon-user"></span>
The u should be small in User.id:
<span class="glyphicon glyphicon-user"></span>

Why isn't the paragraph tag working?

I'm using Django but for some reason the <h2> tag displays article.title with no problem but the <p> tag won't display anything - even simple text.
{% extends 'base_layout.html' %}
{% block content%}
<h1>Articles List</h1>
<div class="articles">
{% for article in articles %}
<div class="article">
<h2>{{ article.title}}</h2>
<p>TEST TEXT</p>
<p>{{ article.date }}</p>
</div>
{% endfor %}
</div>
{% endblock %}
the base_layout.html is
{% load static from staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Carpe Nocturn</title>
<link rel="stylesheet" href="{% static 'styles.css' %}">
</head>
<body>
<header class="wrapper">
<h1><img src="{% static 'logo.png' %}" alt="Carpe Nocturn" /></h1>
</header>
<div class="wrapper">
{% block content %}
{% endblock %}
</div>
</body>
</html>

Django form doesn't show available values

I'm quite new to Django...
So, I have a model. Notice the two foreign key fields (DeviceProfile model actually has data, but MISMStateSnapshot does not):
class MISMWorkflow(models.Model):
createdAt = models.DateTimeField(default=timezone.now)
currentSnapshot = models.ForeignKey('MISMStateSnapshot', null=True, blank=True, on_delete=models.SET_NULL)
device = models.ForeignKey(DeviceProfile, null=True, blank=True, on_delete=models.SET_NULL, related_name='workflows')
def get_absolute_url(self):
return reverse('{}:workflow_detail'.format(VIEW_NAMESPACE), args=(self.pk,))
And a CreateView:
class WorkflowCreateView(generic.CreateView):
model = MISMWorkflow
fields = '__all__'
template_name = 'mism_web/workflow_create_form.html'
def form_valid(self, form):
form.instance.device = DeviceProfile.objects.get(pk=self.kwargs.get('device_id'))
form.instance.createdAt = timezone.now()
return super(WorkflowCreateView, self).form_valid(form)
And the template:
{% extends 'mism_web/base.html' %}
{% load material_form %}
{% block content %}
<form action="" method="POST">{% csrf_token %}
<!--{{ form.as_p }}-->
{% form form=form %}{% endform %}
<input type="submit" name="_submit" class="btn" value="Save" />
</form>
{% endblock %}
urls:
url(r'^workflow/workflow_create/$', workflow.WorkflowCreateView.as_view(), name='workflow_create_new'),
This is what I see when I go to create page:
There are couple of things wrong with this:
I don't see the calendar/clock widget for the DateTimeField (createdAt) that I expected to see here.
There's no selection input for either currentSnapshot or device fields (Even though there are devices in the DB)
This is not because I am using the django-material plugin. I tested without it and I still get the same "empty" form.
What's the cause of this and how to fix?
EDIT:
This is what I see in the admin panel for `MISMWorkflow', this is exactly the sort of form I expect to see (ofc, I don't want to create foreign key entities from here, just to list them down):
EDIT: The problem seems to happen only when I extend the base template. If I don't use it, I can see the fields properly. For example, template will be like so:
<html>
<body>
<form action="" method="POST">{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="_submit" class="btn" value="Save" />
</form>
<body>
<html>
And I can see the dropdowns now:
Here is my base.html:
{% load static %}
{% load compress %}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="{% static 'mism_web/css/materialize.min.css' %}" media="screen,projection"/>
<link type="text/css" rel="stylesheet" href="{% static 'mism_web/css/helper.css' %}" media="screen,projection"/>
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<!-- TODO: Fix navbar links -->
<body>
<div>
<nav>
<div class="nav-wrapper">
MISM
<a href="#" data-activates="mobile" class="button-collapse">
<i class="material-icons">menu</i>
</a>
<ul class="right hide-on-med-and-down">
<li>
<a href="{% url 'mism_web:index' %}">
<i class="material-icons left">home</i>
Home
</a>
</li>
<li>
<a href="{% url 'mism_web:device_list' %}">
<i class="material-icons left">perm_device_information</i>
Devices
</a>
</li>
<li>
<a href="{% url 'mism_web:workflow_list' %}">
<i class="material-icons left">format_indent_increase</i>
Workflows
</a>
</li>
<li>
{% if user.is_authenticated %}
{{ user.get_username }}
{% else %}
Unknown user
{% endif %}
</li>
</ul>
<ul class="side-nav" id="mobile">
<li>
<a href="{% url 'mism_web:device_list' %}">
<i class="material-icons top">home</i>
Home
</a>
</li>
<li>
<a href="{% url 'mism_web:device_list' %}">
<i class="material-icons top">perm_device_information</i>
Devices
</a>
</li>
<li>
<a href="{% url 'mism_web:workflow_list' %}">
<i class="material-icons top">format_indent_increase</i>
Workflows
</a>
</li>
<li>
{% if user.is_authenticated %}
{{ user.get_username }}
{% else %}
Unknown user
{% endif %}
</li>
</ul>
</div>
</nav>
</div>
<div class="container">
{% block content %} {% endblock %}
</div>
<script type="text/javascript" src="{% static 'mism_web/js/jquery-3.2.1.min.js' %}"></script>
<script type="text/javascript" src="{% static 'mism_web/js/materialize.min.js' %}"></script>
<script type="text/javascript" src="{% static 'mism_web/js/helper.js' %}"></script>
</body>
</html>
So, it's the base.html interfering with the form display in some way. I have no idea how.
From what I understood. It seems you havent initialized the select in materialize.
Try adding a script tag in the html file with the form with the following contents:
$(document).ready(function() {
$('select').material_select();
});
You may need to initialize the datepicker plugin too to display the datepicker calendar.
More about this can be found here:
http://materializecss.com/forms.html

Blank section appear when using Jinja2/Flask

I'm creating a website and it works fine when i use direct html. Now i want to use Jinja2 to render my template and there is something wrong. You can see that there is a blank space on top of my page here http://kgroupman.azurewebsites.net/ but it works fine with firefox. Inspect element do not point out that blank section and there is no padding or margin and there is nothing wrong with the source. Please help!
Here is the code:
base.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>
{% block page_title %}{% endblock %}
</title>
<!--BASE CSS-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="{{url_for('static', filename='css/base.css')}}" />
<!--ADDITIONAL CSS-->
{% block additional_css %}
{% endblock %}
<!--BASE SCRIPT-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<!--ADDITIONAL SCRIPT-->
{% block additional_script %}
{% endblock %}
</head>
<body>
<section class="header">
<nav class="navbar navbar-default navbar-static-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><span><img src="{{url_for('static', filename='imgs/4logo.png')}}" id="logo"></span></a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right"></ul>
</div>
</div>
</nav>
</section>
<section class="body">
<div class="left-panel">
{% block body_left %}
{% endblock %}
</div>
<div class="right-panel">
{% block body_right %}
{% endblock %}
</div>
</section>
<section class="footer">
<span>#Ngo Tuan Khoa - 2016</span>
</section>
</body>
</html>
login.html
{% extends "base.html" %}
{% block page_title %}Đăng nhập | Quản lý nhóm{% endblock %}
{% block additional_css %}
<link rel="stylesheet" href="{{url_for('static', filename='css/login.css')}}" />
{% endblock %}
{% block additional_script %}
<script src="../static/script/login.js"></script>
{% endblock %}
{% block body_left %}
<div class="login-form">
<p><img id="login-icon" src="{{url_for('static', filename='imgs/user.jpg')}}"></p>
<form action="" method="POST">
<p>Tên đăng nhập</p>
<p><input type="text" class="input-field" placeholder="Username"></p>
<p>Mật khẩu</p>
<p><input type="password" class="input-field" placeholder="Password"></p>
<p><input type="button" class="btn-login" value="Đăng nhập"></p>
</form>
</div>
{% endblock %}
{% block body_right %}
<img src="{{url_for('static', filename='imgs/wall.jpg')}}" height="100%" class="img-responsive">
{% endblock %}
It's a character at the top of your body
Solution found. Delete login.html and recreate it. There's must be an invisible character that i can't see somehow!

Categories