I'm trying to incorporate an template tag/inclusion tag into my sidebar for the site. The main section of the page updates properly when I put:
{% if user.is_authenticated %}
<h1> Hello {{ user.username }}
{% else %}
<h1> Hello </h1>
{% endif %}
When I try to use the same principle in my template tag/sidebar, it seems to ignore user.is_authenticated and will always show 'login' and 'register', when it should be just showing 'logout'.
The body of the html (main index page):
{% load Kappa_extras %}
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-2" id="side_section">
{% block sidebar %}
{% get_game_list %}
{% endblock %}
</div>
<!--Main section-->
<div class="col-sm-10" id="main_section">
{% block body %}
{% endblock %}
</div>
</div>
</div>
The get_game_list function from 'Kappa_extras':
from django import template
from Kappa.models import Game, Game_Page
from django.contrib.auth.models import User
register = template.Library()
#register.inclusion_tag('Kappa/sidebar.html')
def get_game_list():
return {'game_list': Game.objects.all()}
and the 'Kappa/sidebar.html':
<div id="side_default_list">
<ul class="nav">
<li>Kappa</li>
{% if user.is_authenticated %}
<li>Log Out</li>
{% else %}
<li>Log In</li>
<li>Register</li>
{% endif %}
</div>
I checked a few older inquires though none of them are working properly. I tried putting request into def get_game_list(request): but it just said did not receive value for the argument. How do I get the sidebar to update properly when user.is_authenticated?
You need to pass the user to your inclusion tag.
#register.inclusion_tag('Kappa/sidebar.html')
def get_game_list(user):
return {'game_list': Game.objects.all(), 'user': user}
Then in your template, call the tag with
{% get_game_list user %}
Alternatively, you can set takes_context=True in your inclusion tag, so that you can access the user from the template context.
#register.inclusion_tag('Kappa/sidebar.html', takes_context=True)
def get_game_list(context):
return {'game_list': Game.objects.all(), 'user': context['user']}
In this case, you don't need to pass the user to the template tag any more.
{% get_game_list %}
See the docs for more information and other examples.
Related
I'm using jazzmin for django admin and mptt. After adding mptt to admin, in jazzmin theme add button disappeared.
I'm using latest versions of all libraries
class CustomMPTTModelAdmin(MPTTModelAdmin):
# specify pixel amount for this ModelAdmin only:
mptt_level_indent = 30
admin.site.register(Menu, CustomMPTTModelAdmin)
Here you can see the admin where button disappeared
When I disable jazzmin or remove Mptt add button returns back on place
INSTALLED_APPS = [
# 'jazzmin',
.....
]
Here you can button returns back
There is also issue was opened on github
https://github.com/farridav/django-jazzmin/issues/126
but I could not find solution for this problem
I was facing the exact same issue while using django-mptt and django-jazzmin together. It seems that the admin template admin/mptt-change-list.html currently does not have the {% change_list_object_tools %} tag present, which causes the Add button to not be rendered.
The solution is to override the mptt-change-list.html template with:
{% extends "admin/mptt_change_list.html" %}
{% load admin_list i18n mptt_admin %}
{% block result_list %}
<div class="row">
<div class="col-12 col-sm-8">
{% if action_form and actions_on_top and cl.show_admin_actions %}{% admin_actions %}{% endif %}
</div>
<div class="col-12 col-sm-4">
{% block object-tools %}
{% block object-tools-items %}
{% change_list_object_tools %}
{% endblock %}
{% endblock %}
</div>
<hr>
<div class="col-12">
{% mptt_result_list cl %}
</div>
{% if action_form and actions_on_bottom and cl.show_admin_actions %}
<div class="row">
<div class="col-12">
{% admin_actions %}
</div>
</div>{% endif %}
</div>
{% endblock %}
I have a page that contains a form. It has 3 buttons, Enter/Leave and Options. My enter and leave button operate just fine, but the options button is supposed to redirect to a list of entries and currently it does not do anything, not even produce errors, which I can't figure out why it's happening.
I feel like I'm missing something very slight, I tried moving the Manager Options button into the form tags but this did not work either, so I'm not sure I'm missing an important piece as I am fairly new to Python/Django.
views.py
class EnterExitArea(CreateView):
model = EmployeeWorkAreaLog
template_name = "operations/enter_exit_area.html"
form_class = WarehouseForm
def form_valid(self, form):
emp_num = form.cleaned_data['adp_number']
if 'enter_area' in self.request.POST:
form.save()
return HttpResponseRedirect(self.request.path_info)
elif 'leave_area' in self.request.POST:
form.save()
EmployeeWorkAreaLog.objects.filter(adp_number=emp_num).update(time_out=datetime.now())
return HttpResponseRedirect(self.request.path_info)
elif 'manager_options' in self.request.POST:
return redirect('enter_exit_area_manager_options_list')
class EnterExitAreaManagerOptionsList(ListView):
filter_form_class = EnterExitAreaManagerOptionsFilterForm
default_sort = "name"
template = "operations/list.html"
def get_initial_queryset(self):
return EmployeeWorkAreaLog.active.all()
def set_columns(self):
self.add_column(name='Employee #', field='adp_number')
self.add_column(name='Work Area', field='work_area')
self.add_column(name='Station', field='station_number')
urls.py
urlpatterns = [
url(r'enter-exit-area/$', EnterExitArea.as_view(), name='enter_exit_area'),
url(r'enter-exit-area-manager-options-list/$', EnterExitAreaManagerOptionsList.as_view(), name='enter_exit_area_manager_options_list'),
]
enter_exit_area.html
{% extends "base.html" %}
{% block main %}
<form id="warehouseForm" action="" method="POST" novalidate >
{% csrf_token %}
<div>
<div>
{{ form.adp_number.help_text }}
{{ form.adp_number }}
</div>
<div>
{{ form.work_area.help_text }}
{{ form.work_area }}
</div>
<div>
{{ form.station_number.help_text }}
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Leave Area</button>
</div>
</div>
</form>
{% endblock main %}
{% block panel_footer %}
<div class="text-center">
<button type="submit" name="manager_options" value="Options">
Manager Options
</button>
</div>
{% endblock panel_footer %}
list.html
{% extends "base.html" %}
{% load core_tags staticfiles %}
{% block head %}
<script src="{% static "js/operations/enter_exit_area_manager_options_list.js" %}"></script>
{% endblock head %}
{% block main %}
{% include 'core/list_view/list.html' %}
{% endblock main %}
You option buttons is really link to another page so you should add it to your template like this. Replacing button-styles class with however you want your button to look.
<a href="{% url 'enter_exit_area_manager_options_list' %}" class="button-styles">
Manager Options
</a>
I'm using flask-bootstrap to use the Bootstrap front-end for a flask web application. Unfortunately, since I've started using flask-bootstrap and flask-nav, I'm not able to display flash messages.
This is the base.html:
{% extends 'bootstrap/base.html' %}
{% block navbar %}
{{ nav.mynavbar.render() }}
{% endblock %}
<html>
<body>
<hr>
<div class='container'>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
{% endwith %}
{% block content %}{% endblock %}
</div>
</body>
</html>
This is one of the view that should flash a message when a change is saved:
#app.route('/model/<model_name>/edit', methods=['GET', 'POST'])
def edit(model_name):
"""Edit model's configuration.
Args:
model_name [str]: The name of the model we want to change the
configuration.
"""
# return to index page if model is not found in the database
model = DSModel.query.filter_by(name=model_name).first()
if not model:
flash('Model {} not found.'.format(model_name))
return redirect(url_for('index'))
# pre-load current model's configuration
form = ConfigurationForm()
# if it's a POST request, it means the user is trying to change the model's
# configuration. Save changes in the database
if request.method == 'POST': # and form.validate_on_submit():
model.configuration.configuration = form.value.data
model.configuration.datetime = datetime.datetime.utcnow()
db.session.add(model)
db.session.commit()
flash('Your changes have been saved.', 'success')
return redirect(url_for('edit', model_name=model_name))
else:
form.value.data = model.configuration.configuration
return render_template('edit.html', form=form)
Finally, this is the __init__.py:
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import Navbar, View
from flask_sqlalchemy import SQLAlchemy
nav = Nav()
#nav.navigation()
def mynavbar():
return Navbar(
'Dashboard',
View('Home', 'index'),
View('Login', 'login')
)
app = Flask(__name__)
Bootstrap(app)
nav.init_app(app)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import views, models
I think there must be something funky with my base.html file, but I'm not terribly familiar with HTML, so I'm not able to find what's wrong. I've looked into examples online (i.e. here), but the format seems to be pretty similar to what I'm doing.
EDIT: This is the edit.html file:
{% extends 'base.html' %}
{% block content %}
<h1>Update configuration</h1>
<form action='' method='post' name='configuration'>
<p>
Please update the current model configuration:<br>
{{ form.value(cols='150', rows='20') }}
<p><input type='submit' value='Save'></p>
</form>
{% endblock %}
Try to edit your base.html to this:
{% extends 'bootstrap/base.html' %}
{% block navbar %}
{{ nav.mynavbar.render() }}
{% endblock %}
<html>
<body>
<hr>
<div class='container'>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</div>
{% block content %}{% endblock %}
</div>
</body>
</html>
I have a the following code for a Form that I have in my Flask application using Wtforms. I use FieldList to use two fields for one part.
class A(Form)
additional = FieldList(FormField(Additional), 'Additional', min_entries=1)
submit = SubmitField('Submit')
class Additional(Form):
choices = [('Funding Mechanism', 'Funding Mechanism'), ('Study Section Name', 'Study Section Name')]
critera = SelectField('Additional Criteria', choices=choices)
input = StringField()
The template uses wtf.quick_form:
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Grants - Find Grant{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Specify</h1>
</div>
<div class="col-md-4">
{{ wtf.quick_form(form) }}
</div>
{% endblock %}
Currently the forms render in a squished and overlapping way like so:
How can I change the code so that it is formated in one line like below? It is a screenshot of #Niklas in Stockholm 's form from his question.
Thank you!
Since your form class A is calling class Additional as a FormField and only adding submit to the field, i added the submit button the Additional form itself and then called it in the view.
In the template, use
{{ wtf.quick_form(form, form_type="inline") }}
It outputs the page like this:
The form_type argument adds the .form-inline to the class attribute.
This is just a hack, surely your form will have more inputs than this, for that, you'll be writing the whole form template yourself.
The issue is that {{ wtf.quick_form(form) }} is calling wtf.form_field() on your FieldList additional in A instead of calling it on additional's subfields. Because of this, I don't think you will be able to use wtf.quick_form() on your particular form.
Instead, try templating your form like this:
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Grants - Find Grant{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Specify</h1>
</div>
<div class="col-md-4">
<form class="form form-horizontal" method="post" role="form">
{{ form.hidden_tag() }}
{{ wtf.form_errors(form, hiddens="only") }}
{% for subfield in form.additional %}
{{ wtf.form_field(subfield) }}
{% endfor %}
{{ wtf.form_field(form.submit) }}
</form>
</div>
{% endblock %}
You can read more about wtf.form_field() on the Flask-Bootstrap documentation site.
I'm creating a web app with django 1.2.4.
I am using contrib.auth.views.login, I have followed every step but it seems I have forgotten something cause I don't see the login form. Here is my folder structure:
/templates/
base.html
/myapp/
object_list.html
...
/registration/
login.html
...and here is my login.html:
{% extends "base.html" %}
{% block mylogin %}
<div class="horizontal">
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form action="{% url django.contrib.auth.views.login %}" method="post">
{% csrf_token %}
<div class="login_box">
<div class="login_text">{{ form.username.label_tag }}</div><div class="login_input">{{ form.username }}</div>
<div class="password_text">{{ form.password.label_tag }}</div><div class="password_input">{{ form.password }}</div>
<input id="button_login" type="submit" value="" />
</div>
</form>
</div>
{% endblock %}
...and in my base.html I have:
<div id="some_div">
{% block mylogin %} {% endblock %}
</div>
I have a basestyle.css included in base.html and the other templates inherit correctly too... it seems to be a block problem...
Any solution??
Thnak you
Instead of inserting of a block I used the include tag in base.html, just like this:
{% include "registration/login.html" %}
If you’d prefer not to call default (django provided) template registration/login.html, you can pass the template_name parameter via the extra arguments to the view in your URLconf.
For example, this URLconf line would use myapp/login.html instead:
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'myapp/login.html'}),
Reference : Django official documentation
It solves my problem. Hope this works for others.