Want to Authenticate only Superuser - django

I want want give access to an html file to only the Superuser.
Just how {% if user.is_authenticated %} authenticates all the users including the superusers, is there any way i can only authenticate superusers and not non superusers?
{% block title %}base{% endblock %}
{% block content %}
{% if user.is_authenticated %}
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{% block title %}Django{% endblock %}</title>
</head>
<body>
<main>
{% block content %}
{% endblock %}
</main>
</body>
</html>
{% else %}
<p>You are not logged in</p>
login
{% endif %}
{% endblock %}

{% if user.is_authenticated and user.is_superuser %}
This statement should return True if a user is superuser and authenticated.

{% if user.is_authenticated and user.is_superuser %}
<li class="nav-item">
<a href="/admin" target="_blank"> <button type="button" class="btn btn-primary mx-1">
Admin
</button></a>
</li>
{% endif %}
**This Works Fine**

Related

Flask.flash messages not available through extended template

I am having trouble with sending flashed messages to a route that extends its layout from another template. This message shows up just fine if use the message in the layout.html which makes me believe that rendering login.html first will render layout.html and use the flashed message there and not pass it to my /login route. How are you able to call this message in an extended template? I am using the jijna with syntax taken from here to be able to have the message variable available within my mainblock. Flask's documentation does not specify this either.
app.py
#app.route("/login", methods=["POST", "GET"])
def login():
# Forget any previous user
if session.get("user_id"):
session.pop("user_id")
if request.method == "POST":
# Create connection cursor
cursor = mysql.connection.cursor()
# Query database for email
cursor.execute("SELECT id, email, password FROM users WHERE email = %s", [request.form.get("email")])
row = cursor.fetchone()
print(row)
if row is None:
print("WHY")
flash("Invaid user")
return redirect("login")
My layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hoook - {% block title %}{% endblock %}</title>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, width=device-width">
<link href="/static/favicon-16x16.png" rel="icon">
<link href="/static/style.css" rel="stylesheet">
<!-- Scripts -->
<script src="https://kit.fontawesome.com/542c2d099e.js" crossorigin="anonymous"></script>
<script src="/static/mainJS.js"></script>
</head>
<body>
<div class="page-wrapper">
<header>
<nav class="main-navbar">
{% if request.path == "/login" %}
<div class="navbar-container login-container">
{% else %}
<div class="navbar-container">
{% endif %}
<div>
{% if request.path == "/login" %}
<img src="/static/hoook_logo_blue.png" alt="Hoook Logo" height="50" width="150">
{% else %}
<img src="/static/hoook_logo.png" alt="Hoook Logo" height="50" width="150">
{% endif %}
</div>
{% if request.path != "/login" %}
<div>
{% if session["user_id"] %}
{# change nav bar for logged in users #}
{% else %}
{# work on this nav bar for unlogged in users #}
{% if request.path == "/signup" %}
<a class="navbar-link" href="/login">Sign in</a>
{% endif %}
{% endif %}
</div>
{% endif %}
</div>
</nav>
</header>
</div>
<main>
{% if request.path == "/login" %}
<div class="top-container signup-container">
{% else %}
<div class="top-container">
{% endif %}
{% with messages = get_flashed_messages() %}
{% block main %}{% endblock %}
{% endwith %}
</div>
</main>
<footer>
</footer>
</body>
</html>
My login.html
{% extends "layout.html" %}
{% block title %}
Login
{% endblock %}
{% block main %}
<div class="login-div">
<div>
<h1 class="color-control">Sign in to Hoook</h1>
</div>
<div class="login-input-bx">
<form action="/login" method="post" autocomplete="off">
<div class="form-control login-form-control">
<label class="login-label color-control" for="email">Email address</label>
<input class="login-input" type="text" name="email" id="email" required autofocus>
</div>
<div class="form-control login-form-control">
<label class="login-label color-control" for="password">Password</label>
<input class="login-input" type="password" name="password" id="password" required readonly onfocus="this.removeAttribute('readonly')">
</div>
<button class="btn btn-login" type="submit">Sign in</button>
</form>
</div>
{% if messages %}
{% for msg in messages %}
<div class="flashed-messages-div">
<p class="signup-para" id="login-flashed-messages">Error: {{ msg }}</p>
</div>
{% endfor %}
{% endif %}
<div class="signup-link-div">
<p class="color-control signup-login-font">New to Hoook? <a class="signup-link-anchor" href="/signup">Create an account</a>.</p>
</div>
</div>
{% endblock %}
Update
I guess I could do something like make_response instead as seen here. and just use:
response = make_response(render_template("login.html", message = "Invalid user"), 302)
return response
However I am curious if there is a way to pass the flashed message through instead.
I have had the same issue. Instead of:
return redirect("login")
try with:
return render_template("login.html")
The flashed message works that way for me.

Django template tag content missing when extending admin app base template

So I am creating a page in my Django project that essentially just uses the Django admin app header and footer.
I have a template folder in the root of my project where I have my base.html.
/templates/admin/base.html
{% load i18n static %}<!DOCTYPE html>
{% load static %}
{% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %}
<html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'js-stack/assets/css/spark-styles.css' %}" />
<link rel="stylesheet" type="text/css" href="{% block stylesheet %}{% static "admin/css/base.css" %}{% endblock %}" />
{% block extrastyle %}{% endblock %}
{% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% block stylesheet_rtl %}{% static "admin/css/rtl.css" %}{% endblock %}" />{% endif %}
{% block extrahead %}{% endblock %}
{% block blockbots %}<meta name="robots" content="NONE,NOARCHIVE" />{% endblock %}
</head>
{% load i18n %}
<body class="{% if is_popup %}popup {% endif %}{% block bodyclass %}{% endblock %}"
data-admin-utc-offset="{% now "Z" %}">
<!-- Container -->
<div id="container">
{% if not is_popup %}
<!-- Header -->
<div id="header">
<div id="branding">
{% block branding %}{% endblock %}
</div>
{% block usertools %}
{% if has_permission %}
<div id="user-tools">
{% block welcome-msg %}
{% trans 'Welcome,' %}
<strong>{% firstof user.get_short_name user.get_username %}</strong>.
{% endblock %}
/ View Analytics /
{% block userlinks %}
{% if site_url %}
{% trans 'View site' %} /
{% endif %}
{% if user.is_active and user.is_staff %}
{% url 'django-admindocs-docroot' as docsroot %}
{% if docsroot %}
{% trans 'Documentation' %} /
{% endif %}
{% endif %}
{% if user.has_usable_password %}
{% trans 'Change password' %} /
{% endif %}
{% trans 'Log out' %}
{% endblock %}
</div>
{% endif %}
{% endblock %}
{% block nav-global %}{% endblock %}
</div>
<!-- END Header -->
{% block breadcrumbs %}
<div class="breadcrumbs">
{% trans 'Home' %}
{% if title %} › {{ title }}{% endif %}
</div>
{% endblock %}
{% endif %}
{% block messages %}
{% if messages %}
<ul class="messagelist">{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message|capfirst }}</li>
{% endfor %}</ul>
{% endif %}
{% endblock messages %}
<!-- Content -->
<div id="content" class="{% block coltype %}colM{% endblock %}">
{% block pretitle %}{% endblock %}
{% block content_title %}{% if title %}<h1>{{ title }}</h1>{% endif %}{% endblock %}
{% block content %}
{% block object-tools %}{% endblock %}
{{ content }}
{% endblock %}
{% block sidebar %}{% endblock %}
<br class="clear" />
</div>
<!-- END Content -->
{% block footer %}<div style="padding: 10px 40px;" id="footer"><img src="{% static 'wifispark-logo.png' %}"></div>{% endblock %}
</div>
<!-- END Container -->
</body>
</html>
So this is a copy of the admin app base.html, but with a few modificatio0ns such as an image in the footer. This is all working as expected when I log into the admin app.
I also have another app called 'analytics' inside my project. Below is the template for it where I have extended the admin/base.html.
{% extends "admin/base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid">
</div>
{% endblock content %}
Now, when I view my analytics page it loads with all the expected header and footer styling from the admin/base.html, but there is content missing such as the admin app title and the menu links, both of which are pulled through from admin app template tags.
Can anyone shed any light on what I am doing wrong or am missing?
Many thanks,
James
In your View, the one that renders the analytics page make sure you pass user, site_header, has_permission, and site_url as parameters.
These parameters can be extracted like this:
from django.contrib.admin import AdminSite
class MyAdminSite(admin.AdminSite):
pass
mysite = MyAdminSite()
And then return them while rendering your template:
def get(self, request):
return render(request, 'analytics.html', {'user': request.user,'site_header': mysite.site_header,'has_permission': mysite.has_permission(request), 'site_url': mysite.site_url})
Hope that helps

request.user.first_name does not working in django

I'm trying to build a authentication based view! My html code is:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link href="{% static "css/base.css" %}" rel="stylesheet">
</head>
<body>
<div id="header">
<span class="logo">Bookmarks</span>
{% if request.user.is_authenticated %}
<ul class="menu">
<li {% if section == "dashboard" %}class="selected"{% endif %}>My dashboard</li>
<li {% if section == "images" %}class="selected"{% endif %}>Images</li>
<li {% if section == "people" %}class="selected"{% endif %}>People</li>
</ul>
{% endif %}
<span class="user">
{% if request.user.is_authenticated %}
Hello {{ request.user.first_name }}, Logout
{% else %}
Log-in
{% endif %}
</span>
</div>
</body>
</html>
Here the line:
request.user.first_name
supposed to show the logged in username according to Django By Example book.
also when I'm changing the password in firefox it shows this massage:
But in chrome it works fine in changing password, although the name is not showing in both browser!
My Login page html code is :
{% extends "base.html" %}
{% block title %}Log-in{% endblock %}
{% block content %}
<h1>Log-in</h1>
{% if form.errors %}
<p>
Your username and password didn't match.
Please try again.
</p>
{% else %}
<p>Please, use the following form to log-in:</p>
{% endif %}
<div class="login-form">
<form action="{% url 'login' %}" method="post">
{{ form.as_p }}
{% csrf_token %}
<input type="hidden" name="next" value="{{ next }}" />
<p><input type="submit" value="Log-in"></p>
</form>
</div>
{% endblock %}
I'm stuck really bad :(
This is silly! The problem was I didn't set the user's firstname!
But the second problem is still happening!
i had same issue, but after some research, i found this solution
so try to edit the variable from {{ request.user.first_name }} TO {{ request.user.username}}, so is username not firstname.

How to display layout content in Twig template based on a view

I have some content in my layout that are not supposed to be displayed in some pages.
E.g.: When a user is registering for the site my default frontpage sidebar should not be displayed:
<!DOCTYPE html>
<html>
<head>
{% block head %}
<link rel="stylesheet" href="style.css" />
<title>{% block title %}{% endblock %} - My Webpage</title>
{% endblock %}
</head>
<body>
<div id="content">
<div id="sidebar">
{% block sidebar %}
{% render "/layout/sidebar" %}
{% endblock %}
{% block content %}{% endblock %}
</div>
</div>
<div id="footer">
{% block footer %}
© Copyright 2011 by you.
{% endblock %}
</div>
</body>
</html>
In the above code:
{% block sidebar %}
should display some advertising instead!
So:
Something like:
{% if SOMEVIEW == TRUE %}
{% block sidebar %}
{% else %}
{% block advertising %}
{% endif %}
What expression could I use in my IF to accomplish that job?
Thanks in advance
You can look at
How to check if an user is logged in Symfony2 inside a controller?
and http://symfony.com/doc/current/book/security.html#access-control-in-templates
In the view you can use {{ is_granted('IS_AUTHENTICATED_FULLY') }} to check if a user is logged in.
Hope it's helpful.
Best regard.
I came accross to the solution here http://symfony.com/doc/current/cmf/bundles/core.html#twig:
app.request.attributes.get('_template').get('name')
will return the route name so that I can handle it inside my twig files.

Slim, Twig - how to pass var to Twig to base template

I would like to show the number of unreaded msgs in User Panel Box which will appear everytime when user is logged in.
How to pass the number of msg from controler to the user panel box which is included in base layout?
I can't use routes for that because the panel appears on all pages (index as well).
Now i'm sending it using global session but i think it could be done better. Any clues ?
Controler:
if(isset($_SESSION['user_id'])){
$unreaded=Model::factory('Message')->filter('getUnreadedGroups',$_SESSION['user_id']);
$_SESSION['unreaded']=$unreaded->opened;}
Base layout
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="/css/reset.css" />
<link rel="stylesheet" href="/css/style.css" />
<title>{% block page_title %} {% endblock %}</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="/js/jquery.scripts.js"></script>
</head>
<body>
<div id="all">
<div id="top-container">
<div id="logo">test</div>
<div id="search-box"></div>
</div>
<div id="left-side">
<div class="menu">
<ul>
<li class="nav_dashboard active">Strona główna</li>
<li class="nav_graphs">Wzory</li>
<li class="nav_forms">Najnowsze</li>
<li class="nav_typography">Najlepiej oceniane</li>
</ul>
</div>
</div>
<div id="page">
{% block content %} {% endblock %}
</div>
<div id="right-side">
<div id="login-container">
{% if session.user_id is defined %}
{% include 'user_panel.php' %}
{% else %}
{% include 'login_form.php' %}
{% endif %}
</div>
</div>
</div>
</body>
</html>
User Panel Box
<div class="login-top" id="login-form-top">
<div id="welcome">Witaj, <span>John Doe</span></div>
<p id="last-login">Ostatnie logowanie:</p>
<div id="logout-msg-container">
<div class="logut">Wyloguj</div>
<a id="msg-number" href="/profil/wiadomosci">
<span class="number">
{% if session.unreaded >0 %}
{{ session.unreaded }}
{% else %} 0
{% endif %}
</span>
</a>
</div>
</div>
<div class="menu">
<p class="header">Profil użytkownika</p>
<ul>
<li>Twoje Dane</li>
<li>Twoje zbiory</li>
<li>Twoje wiadomości</li>
</ul>
</div>
Typical template
{% extends 'layout.php' %}
{% block page_title %}Najnowsze pliki{% endblock %}
{% block content %}
<div id="page-top">
<h1>Najnowsze</h1>
<p>+ <span class="blue">12</span> wzorów</p>
</div>
<div id="main-topvote">
<div class="title">Najnowsze<span>( ostatni tydzień )</span></div>
<div class="content">
{% for file in files %}
<p>{{ file.idFile }}<br/> {{ file.date_add }}<br/> {{ file.desc }}<br/> {{ file.title }}<br/><br/></p>
{% else %}
<p>There are currently no articles.</p>
{% endfor %}
</div>
</div>
{% endblock %}
I havent tested this ( https://github.com/fabpot/Twig/issues/293 ):
Base layout:
...
<div id="right-side">
{% block side %}
{% block side-login %}
{% if session.user_id is defined %}
{% include 'user_panel.php' %}
{% else %}
{% include 'login_form.php' %}
{% endif %}
{% endblock %}
{% endblock %}
</div>
...
Typical template:
...
{% block side %}
{% set count = 12 %}
{% block side-login %}
{{ parent() }}
{% endblock %}
{% endblock %}
...
So you can use {{count}} in your User Panel Box.
You can also try to skip the side-login block definition .. but i am not sure.