I am from PHP,Zend world and new to django python. It might be a dump question, but I tried several ways, it didn't work, please advice me .
I am using jinja2 with Django 1.7. I am trying to put the 'APPLICATION_TITLE' in settings.py
APPLICATION_TITLE = "My Application"
I want this value to be used in layout.jinja.html as the title
layout.jinja.html
<head>
<!-- APPLICATION_TITLE should go below -->
<title>{{ ???????????? }}</title>
</head>
Please guide me.
You can create a context processor:
your_app/context_processors.py
from django.conf import settings
def application_title(request):
return {'APPLICATION_TITLE': settings.APPLICATION_TITLE}
settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
...
"your_app.context_processors.application_title",
)
layout.jinja.html
<head>
<title>{{ APPLICATION_TITLE }}</title>
</head>
Related
Using Crispy Forms with Django, I can only get a TemplateDoesNotExist error when using any feature of Crispy Forms.
As I'm new to Crispy Forms (which seems to be universally recommended for quickly making forms look better), I have followed the instructions at https://django-crispy-forms.readthedocs.io/en/latest/install.html and as far as I know, the installation is correct (installed using pip and changes in settings.py). I am running this in a virtual environment (the .venv folder referred to below) on a Windows machine.
I have even created a new project specifically to look at this, with absolutely minimal content, and the same problem persists. The project is called 'stuff' and the single app in it 'other'.
settings.py
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'other',
'bootstrap4'
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
...
models.py
from django.db import models
class Mine(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
forms.py
from django import forms
from .models import Mine
class MineForm(forms.ModelForm):
class Meta:
model = Mine
fields = ('name','email')
views.py
from django.shortcuts import render
from .forms import *
def idx(request):
tform = MineForm()
return render(request,'test.html',{'aform': tform})
test.html
{% load bootstrap4 %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TestThing</title>
</head>
<body>
<form action="/">
{% csrf_token %}
{{ aform|crispy }}
</form>
</body>
</html>
results of pip freeze
asgiref==3.6.0
beautifulsoup4==4.11.2
Django==4.1.7
django-bootstrap4==22.3
django-crispy-forms==2.0
soupsieve==2.4
sqlparse==0.4.3
tzdata==2022.7
error reported on debug page
TemplateDoesNotExist at /
bootstrap4/uni_form.html
Template-loader postmortem
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\ProjectDir\.venv\lib\site-packages\django\contrib\admin\templates\bootstrap4\uni_form.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\ProjectDir\.venv\lib\site-packages\django\contrib\auth\templates\bootstrap4\uni_form.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\ProjectDir\other\templates\bootstrap4\uni_form.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\ProjectDir\.venv\lib\site-packages\bootstrap4\templates\bootstrap4\uni_form.html (Source does not exist)
It looks to me like Crispy can't see the templates which should have been installed. Or perhaps there's something else I'm supposed to download or create?
I wanted to quickly tidy a form up in my Django project before moving on to more pressing matters, and hours later I still can't get Crispy Forms to function at all (it would have been quicker to sort this in other ways). It's clear I'm missing something, but what?
Other Weird and Wonderful things I've tried
Not all of these might be logical, but hey!
deliberately putting the wrong string in CRISPY_TEMPLATE_PACK -- this results in an error suggesting I need to use bootstrap3, bootstrap4, or uni_form. Although repeating this experiment keeps the error reported above (with the misspelling)
removing the django-bootstrap4 module and loading from CDN (no difference)
creating a blank HTML file at the path shown for the template, which just fails to render the form
using {% crispy aform %} - same result
As of django-crispy-forms 2.0 the template packs are now in separate packages.
You will need to pip install crispy-bootstrap4 and add crispy_boostrap4 to your list of INSTALLED_APPS.
I am working on a feedback function and trying to pass data (list of integers) from FLASk to javaScript but there seems to a missing which I can not figure out. if someone helps me it would be great
->I also read similar posts but most of the datatypes were url or dictionary and not integers.
here is where I have problems with the code:
from flask import Flask, render_template
app = Flask (__name__)
#app.route('/new')
def new() :
valu=[10,0,0,10,0,10,0]
return render_template('feedback.html', value=valu)
if __name__ == '__main__':
app.run(debug = True)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Feedback page</title>
</head>
<body>
<script> document.write(value);</script>
</body>
</html>
I believe you are not rendering your jinja template variable correctly for "value" in your javascript line. Should be something like:
<script>document.write({{ value }});</script>
I'm developing an application that needs a global variable. Fortunately, it is working despite Eclipse complaining about the way I used the global variable. To use as an example in this question, I created an application (which works!) that uses a global variable as a page counter. Here is the code:
My __init__.py file:
counter = 0
My views.py
from AccessCounter import counter
from django.shortcuts import render
def conterf(request):
global counter
counter +=1
context = {
'counter' : counter,
}
return render(request, 'AccessCounter/index.html', context)
And Eclipse is complaining that I have a "Unsed import: counter" at line "from AccessCounter import counter", but if I remove this line, the counter does not work with this error:
name 'counter' is not defined
I don't think that the following information is relevant, but here they are...
My index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Access counter: {{ counter }}
</body>
</html>
and my url.py file:
from django.contrib import admin
from django.urls import path
from AccessCounter import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.conterf, name='counter'),
]
How can I include "in-line" javascript in a Flask template for performance but keep the code in a separate file in the static folder for organization? Something like this is what I'm looking for.
<script>
{% include_from_static 'in-line.js' %}
</script>
This doesn't seem possible with the normal include directive and url_for. If I need a custom function for this, how do I go about writing it? (There's a related example on another thread, but I don't understand enough to adapt the code for this.)
Well, you can pass the root of your Flask project to PackageLoader. The downside will be that you must have to prefix each file to the template and static folder.
app.py
from flask import Flask
from jinja2 import Markup, PackageLoader, Environment
app = Flask(__name__)
def include_file(name):
return Markup(loader.get_source(env, name)[0])
loader = PackageLoader(__name__, '')
env = Environment(loader=loader)
env.globals['include_file'] = include_file
#app.route('/')
def index():
return env.get_template('templates/page.html').render()
if __name__ == '__main__':
app.run()
static/script.js
console.log('hello world');
templates/page.html
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<script type="text/javascript">
{{ include_file('static/script.js') }}
</script>
</body>
</html>
I need to link a CSS file to a simple hmtl page and it just doesn't work! I have red the Docs and watched like 10 Videos that develop on Linux Systems, but non of them come along with the Config of Windows!
for some reason the version I'm using creates the Tree in this way! (correct me if am wrong, because am really new to Django)
mysite
\blog
\static
style.css
\templates
index.html
__init__.py
models.py
tests.py
views.py
\mysite
url.py
settings.py
wsgi.py
manage.py
I added the url to settings.py file:
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('assets','blog/static'),
views.py looks like this :
from django.http import HttpResponse,Http404,HttpRequest
from django.shortcuts import render_to_response
def change_form(request):
return render_to_response('index.html')
then I did the Collectstatic command, and a Dir under the name (assets) is added to the root Directory of mysite
and my index.html looks like this
{& load static &}
<!DOCTYPE html>
<html>
<head>
<!--Meta tags-->
<meta charset="utf-8">
<!--Title-->
<title>Menu Notification Badges</title>
<!--Stylesheets-->
<link rel="stylesheet" href="{% static 'assets/css/styles.css' %}">
</head>
and I'm getting this Error now :
TemplateSyntaxError at /change-form/
Invalid block tag: 'static'
Request Method: GET
Request URL: http://localhost:8000/change-form/
Django Version: 1.4.5
Exception Type: TemplateSyntaxError
Exception Value:
Invalid block tag: 'static'
Exception Location: C:\Python27\lib\site-packages\django\template\base.py in invalid_block_tag, line 321
Python Executable: C:\Python27\python.exe
Python Version: 2.7.3
Python Path:
['E:\\DjangoSites\\mysite',
'C:\\Windows\\system32\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages']
Server time: Sat, 27 Apr 2013 09:57:21 +0300
Error during template rendering
In template E:\DjangoSites\mysite\blog\templates\index.html, error at line 13
Invalid block tag: 'static'
3 <html>
4 <head>
5
6 <!--Meta tags-->
7 <meta charset="utf-8">
8
9 <!--Title-->
10 <title>Menu Notification Badges</title>
11
12 <!--Stylesheets-->
13 <link rel="stylesheet" href="{% static 'assets/styles.css' %}">
PLEASE DON'T Direct me to the DOCS! and NOT a Solution with LINUX file System!
THIS is the kindda things that makes me doubt why I chose to be a WebDev!
{& load static &}
should probably be
{% load static %}
I faced similar issue in windows so this is what i did to server my static page with my CSS
make a folder named media and place all your css and js file there and now do following step
settings.py
MEDIA_ROOT = "".join(os.path.join(os.path.dirname(file), 'media').replace('\','/'))
STATICFILES_DIRS = (
os.path.join(os.path.dirname(file),'static').replace('\','/'),
os.path.join(os.path.dirname(file),'media').replace('\','/'),
)
STATIC_DOC_ROOT = '/path/to/media'
urls.py
make a mapping of that folder as a url
(r'^site_media/(?P.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
HTML(in your media folder all CSS and js should be there)
script src="{{MEDIA_URL}}bootstrap/js/bootstrap.min.js">
script src="{{MEDIA_URL}}dropzone/dropzone.js">
views.py
def char(request):
t = get_template('name.html')
html = t.render(Context({'MEDIA_URL':'http://www.google.com/site_media/'}))
return HttpResponse(html)
this will solve your problem.