I'm trying to load a static css file but to no avail:
home.html:
{% extends 'base.html' %}
{% block body%}
{% load static %}
<link rel="stylesheet" href="{% static 'home/style.css' %}" type="text/css">
<div class="container">
<br/>
<form method="post">
{% csrf_token %}
{{ form.post }}
<br />
<button type="submit">Submit</button>
</form>
<h2>{{ text }}</h2>
{% for post in posts %}
<h1>{{ post.post }}</h1>
<p>Posted </b> on {{ post.created }}</p>
{% endfor %}
</div>
{% endblock %}
style.css:
.HomeForm {
size:20;
}
forms.py:
class HomeForm(forms.ModelForm):
post = forms.CharField(widget=forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'How are you feeling?',
'size': '20',
}
))
I have a feeling I'm loading the static file in the wrong place, whats the solution? Thanks in advance.
You are loading the css file correctly. But that is not how you apply css classes to django forms.
Firstly, You are already giving bootstrap attributes to your field in your forms.py.
Now to apply the css classes change the following.
style.css
doesnt matter what you name your classes. No need to name them same as your Form name.
.home-post {
size:30; // Increase this to see difference
}
Now in your home.html add the class to your form. (Look for the comment). So now all the elements inside this container have size attribute too.
{% extends 'base.html' %} {% block body%} {% load static %}
<link rel="stylesheet" href="{% static 'home/style.css' %}" type="text/css">
<div class="container home-post"> <!--This is how you need to apply-->
<br/>
<form method="post">
{% csrf_token %} {{ form.post }}
<br />
<button type="submit">Submit</button>
</form>
<h2>{{ text }}</h2> {% for post in posts %}
<h1>{{ post.post }}</h1>
<p>Posted on {{ post.created }}</p>
{% endfor %}
</div>
{% endblock %}
EDIT:
Looks like you're using bootstrap but don't seem to load it. Add bootstrap if you didn't already add it in your base.html
Related
I have one template called skeleton.html
<head>
</head>
<body>
<div>
Some other code
</div>
<div>
{% block contact_info %}
{% endblock contact_info %}
</div>
</body>
And my other view is say home.html
{% extends "skeleton.html" %}
{% block contact_info %}
<div class="overflow-hidden">
<h4>Phone</h4>
<p class="lead">
{{ phone }}
</p>
</div>
{% endblock contact_info %}
So is this possible that I can use the block (contact_info) to any other template? Is there any way to reuse and render this block to another template file (e.g about.html)?
you can use include
for example
in your main template
{% include 'yourapp/yourtemplate.html' %}
I was working a project on mine, in which I needed to provide a class to a field in form which is a input box, but don't know how to do so.
My Template:
{% extends 'diary/base.html' %}
{% block title %}Register{% endblock title %}
{% block content %}
{% load staticfiles %}
<link rel= "stylesheet" type= "text/css" href = "{% static 'users/register.css' %}">
<div id="login-box">
<div class="left-box">
<h1>Register</h1>
<form action="{% url 'register' %}" method="post">
{% csrf_token %}
{% for non_field_error in form.non_field_errors %}
<p>{{ non_field_error }}</p>
{% endfor %}
{% for field in form %}
{{ field }}
{% for error in field.errors %}
<p>{{ error }}</p>
{% endfor %}
{% endfor %}
<input type="submit" value="SIGN UP" name="signup-button" class="signup-btn">
</form>
</div>
<div class="right-box">
</div>
</div>
{% endblock content %}
In this specific part:
{% for field in form %}
{{ field }}
{% for error in field.errors %}
I want to provide a class to {{ field }}.
I tried this:
{{ field(class="txtb") }}
This is how I use to provide a class in Flask, but in Django this didn't worked.
Any Help Would Be Appreciated!
django-widget-tweaks
I'm using django-widget-tweaks module for set HTML attribute in templates.
installation
install module using pip install django-widget-tweaks
add to INSTALLED_APPS in settings.py
INSTALLED_APPS = [
...
'widget_tweaks',
...
]
{% load widget_tweaks %} in templates file
usage
in templates code:
{% load widget_tweaks %}
...
{% for field in form %}
{% render_field field class="txtb" %}
...
in HTML, looks like this:
<input class="txtb" ... ...>
reference django-widget-tweaks github page for more information.
manually
Detailed description is in here
forms.py:
class YourForm(forms.ModelForm):
modelfield = forms.CharField(
...,
widget=forms.TextInput(
attrs={
'class': 'txtb'
}
}
)
class Meta:
model = ...
fields = ...
And I have a lot of information about django to simpleisbetterthancomplex.com
django-widget-tweaks also learned here
I am currently trying to do some customization to the skin of the django admin panel, to make it more in line with our brand. Currently we use django-jet to spruce up the admin panel. Are custom css/html possible with django-jet? All of the comments say that I should change some html files, but I think those files are hidden from my project because django-jet takes care of them? If anyone could point me in the right direction it would be appreciated.
Thank you
This topic already discussed in django-jet github page
I will simply try to rephrase provided solution with my own words
Create your_app/templates/admin/ folder if doesn't exist
Under this folder create base_site.html file
Copy one of the following code to this file and customize based on your needs
Simple code
{# Template: your_app/templates/admin/base_site.html #}
{% extends "admin/base_site.html" %}
{% load static i18n %}
{# Setup favicon #}
{% block extrahead %}<link rel="shortcut icon" type="image/png" href="{{MEDIA_URL}}your_logo.png"/>{% endblock %}
{# Setup browser tab label #}
{% block title %}{{ title }} | {% trans "Your title" %}{% endblock %}
{# Setup branding #}
{% block branding %}
<h1 id="site-name">
<a href="{% url 'admin:index' %}">
{# Your logo here #}
<img style="background-color: white" src="{{MEDIA_URL}}your_logo.png" alt="Your Company Name" height="50%" width="50%">
<br><br>
</span> {% trans "Your Branding" %}
</a>
</h1>
{% endblock %}
More complex
{% extends "admin/base.html" %}
{% load static i18n %}
{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}
{% block branding %}
<h1 id="site-name">
<span class="icon-jet"></span> {% trans "JET DEMO" %}
</h1>
{% endblock %}
{% block extrastyle %}
{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% static "core/css/branding.css" %}" />
<link rel="stylesheet" type="text/css" href="{% static "core/css/icons/style.css" %}" />
{% endblock %}
{% block nav-global %}
<a href="https://github.com/geex-arts/django-jet" class="sidebar-link icon">
<span class="sidebar-link-label">
<span class="sidebar-link-icon jet-demo-icon-github"></span>
{% trans 'Visit GitHub page' %}
</span>
</a>
<a href="https://github.com/geex-arts/django-jet-demo" class="sidebar-link icon">
<span class="sidebar-link-label">
<span class="sidebar-link-icon jet-demo-icon-github"></span>
{% trans 'Demo site source code' %}
</span>
</a>
{% endblock %}
{% block userlinks %}
{% trans 'Log out' %}
{% endblock %}
{% block footer %}
{{ block.super }}
<!-- Yandex.Metrika counter --><script type="text/javascript"> (function (d, w, c) { (w[c] = w[c] || []).push(function() { try { w.yaCounter32240214 = new Ya.Metrika({ id:32240214, clickmap:true, trackLinks:true, accurateTrackBounce:true, webvisor:true }); } catch(e) { } }); var n = d.getElementsByTagName("script")[0], s = d.createElement("script"), f = function () { n.parentNode.insertBefore(s, n); }; s.type = "text/javascript"; s.async = true; s.src = "https://mc.yandex.ru/metrika/watch.js"; if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); } })(document, window, "yandex_metrika_callbacks");</script><noscript><div><img src="https://mc.yandex.ru/watch/32240214" style="position:absolute; left:-9999px;" alt="" /></div></noscript><!-- /Yandex.Metrika counter -->
<!-- Google Analytics counter -->
<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', 'UA-67280038-1', 'auto');
ga('send', 'pageview');
</script>
<!-- /Google Analytics counter -->
{% endblock %}
#in admin.py file
from django.utils.html import format_html
logo_url= "https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a"
admin.site.site_header = format_html("`<img src={url} height=50 width=50`>", url=logo_url)
Create a admin directory at templates Folder then Create Html File and name it base_site.html . Add Following Content to it .
{% extends "admin/base.html" %}
{% load staticfiles %}
{% block branding %}
<h1 id="site-name">
<a href="{% url 'admin:index' %}">
<img src="{% static 'img/my-logo.png' %}" alt="My Company"/>
</a>
</h1>
{% endblock %}
That's All you are done with custom logo.
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 making my first steps with flask and also jinja2. I have run through some examples but now i try to integrate flask-security and got stuck a bit.
I try to built a modal with an login-form, so I put up a div like this:
<div class="modal">
<h3>Login</h3>
<form action="{{ url_for_security('login') }}" method="POST" name="login_user_form">
{{ login_user_form.hidden_tag() }}
{{ render_field_with_errors(login_user_form.email) }}
{{ render_field_with_errors(login_user_form.password) }}
{{ render_field_with_errors(login_user_form.remember) }}
{{ render_field(login_user_form.next) }}
{{ render_field(login_user_form.submit) }}
</form>
That is the template code taken from the example provided by flask-security. Now i tried to wrap that in
{% extends layout.html %}
{% block loginModal %} ... {% endblock %}
and tried to invoke that in the layout.html by
{% block loginModal %}{% endblock %}
which now i learned is not the way, as the content is rendered and the layout.html only invoked.
Now i tried to put that code directly in the layout.html once by the include statement and as this didn't work i put it in directly.
I also added
{% from "security/_macros.html" import render_field_with_errors, render_field %}
in the first line, which are macros provided by the flask-security package. but all i get is the error:
UndefinedError: 'login_user_form' is undefined (after a long traceback)
I'm totally stuck here, reading jinja2 docs on the website for about an hour now. How can i get this form to work?
Update (I'm sorry, it is a late update):
My layout.html which implements the base layout for all pages
<!doctype html>
<html>
<head>
<title>MyExample</title>
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/style.css') }}">
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='css/gumby.css') }}">
</head>
<body>
<div class=page>
<nav id="navbar-main-nav" class="navbar">
<div class="row">
<a class="toggle" gumby-trigger="#navbar-main-nav #main-nav" href="#"><i class="icon-menu"></i></a>
<h1 class="four columns logo">Logo</h1>
<nav class="five columns pull_right">
<ul id="main-nav">
<li><span>Link1 </span></li>
<li><span>Link2</span><i class="icon-cog" title="Customize"></i></li>
{% if current_user.is_authenticated() %}
<li>Hello {{ current_user.name }}</li>
<li>Logout</li>
{% else %}
<li>Open Modal</li>
<li>Register</li>
{% endif %}
</ul>
</nav>
</div>
</nav>
<div class="modal" id="modal1">
<div class="content">
<a class="close switch" gumby-trigger="|#modal1"><i class="icon-cancel" /></i></a>
<div class="row">
<div class="ten columns centered">
<div class="row">
<div class="five columns">
{% block loginModal %}{% endblock %}
</div>
<div class="five columns">
<!-- register Form -->
</div>
</div>
</div>
</div>
</div>
</div>
{% block body %}{% endblock %}
</div>
<script src="{{ url_for('static', filename='js/libs/modernizr-2.6.2.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/libs/jquery-2.0.2.min.js') }}"></script>
<script gumby-touch="js/libs/" src="{{ url_for('static', filename='js/libs/gumby.min.js') }}"></script>
</body>
</html>
My login.html
{% extends layout.html %}
{% block loginModal %}
{% from "security/_macros.html" import render_field_with_errors, render_field %}
{% include "security/_messages.html" %}
<h3>Login</h3>
<form action="{{ url_for_security('login') }}" method="POST" name="login_user_form">
{{ login_user_form.hidden_tag() }}
{{ render_field_with_errors(login_user_form.email) }}
{{ render_field_with_errors(login_user_form.password) }}
{{ render_field_with_errors(login_user_form.remember) }}
{{ render_field(login_user_form.next) }}
{{ render_field(login_user_form.submit) }}
</form>
{% endblock %}
In an abstract way I want to built something like a widget i can import and use in another template to implement such things only once, like the login form. Later i want to be able to implement lists, that can be placed in a siderbar on every page, without having it implemented on each page by itself. I found Flask Plugable Views but I haven't found a good example to understand the proper usage.
Update 2:
This (updated) implementation renders no form at all, without any error. I think I may have misunderstood the use of blocks.
** Solution **
With help from Mark I found the template context processor very helpful as kind of injection of variables. For some it might be obvious: flask-security provides the Forms as import, therefore my code now looks like this:
from flask.ext.security import LoginForm, RegisterForm
...
#app.context_processor
def inject_userForms():
return dict(login_user_form=LoginForm(), register_user_form=RegisterForm() )
I added the form directly into my layout.html which works well now. What does not work at all is the inclusion of the block. It works if I use blockception, using the login block within a content block.
Your error is:
UndefinedError: 'login_user_form' is undefined
This is coming from the template, which looks like this...
{% extends layout.html %}
{% block loginModal %}
{% from "security/_macros.html" import render_field_with_errors, render_field %}
{% include "security/_messages.html" %}
<h3>Login</h3>
<form action="{{ url_for_security('login') }}" method="POST" name="login_user_form">
{{ login_user_form.hidden_tag() }}
{{ render_field_with_errors(login_user_form.email) }}
{{ render_field_with_errors(login_user_form.password) }}
{{ render_field_with_errors(login_user_form.remember) }}
{{ render_field(login_user_form.next) }}
{{ render_field(login_user_form.submit) }}
</form>
{% endblock %}
Therefore, you are referencing login_user_form, but Jinja2 is complaining that you haven't actually defined login_user_form. You typically define this when you are trying to call the function to render your template..
def my_view():
# ...
return render_template('login.html', login_user_form=login_user_form)
If you don't have the 'login_user_form' passed as an argument to render_template you will get the error.
If you are expecting login_user_form to be defined on the template context elsewhere in your application (such as in a template context processor), then ensure that that part of your application is indeed working.