I am using django-components. Common parts are inherited from parent classes and child classes are registered as components. It is written as follows
components.py
from django_components import component
class Parent(component.Component):
def get_context_data(self, data):
return {
"data": data,
}
#component.register("aaa")
class ChildA(Parent):
template_name = "/aaa.html"
class Media:
css = ["css/my.css", "css/test/aaa.css"]
js = "js/common.js"
#component.register("bbb")
class ChildB(Parent):
template_name = "/bbb.html"
class Media:
css = ["css/my.css", "css/test/bbb.css"]
js = "js/common.js"
When I call the aaa component in a template, I want to call only the Media (css, js) associated with the ChildA class.
xxx.html
{% component "aaa" data=""%}
However, when we check the expanded HTML, even the Media of ChildB is called as shown below.
Expanded final HTML
<script src="js/common.js" ></script>
<script src="js/common.js" ></script>
<link href="css/my.css" media="all" rel="stylesheet">
<link href="css/test/aaa.css" media="all" rel="stylesheet">
<link href="css/my.css" media="all" rel="stylesheet">
<link href="css/test/bbb.css" media="all" rel="stylesheet">
What should I do to avoid calling Media of a component of another class that has the same parent?
We have already confirmed that common.js is called only once when ChildB js is specified empty.
#component.register("bbb")
class ChildB(Parent):
template_name = "/bbb.html"
class Media:
css = ["css/my.css", "css/test/bbb.css"]
js = ""
Related
I'm looking for a way to change link tags with hreflang depends on region or language used on a site. For example:
I have one blog site written in english and on this site I would like to have:
<link rel="alternate" hreflang="en" href="https://example.com" />
<link rel="alternate" hreflang="de" href="https://example.com/de" />
And for German version:
<link rel="alternate" hreflang="de" href="https://example.com/de" />
<link rel="alternate" hreflang="en" href="https://example.com" />
I could do that with statements like this:
{% if request.build_absolute_uri == "https://example.com" %}
{% if request.build_absolute_uri == "https://example.com/de" %}
but what if I will have more then these two paths and my if statement will grow. Is there a better solution?
This answer is inspired by the django cms language_chooser template tag.
You write your own context processor like this:
from cms.utils.i18n import (
get_language_list
get_language_object,
get_public_languages
)
from django.contrib.sites.models import Site
from django.utils.translation import get_language
def language_list_processor(request):
"""
A context processor that adds the available languages to the global context.
"""
context = {}
site = Site.objects.get_current()
if request.user.is_staff:
languages = get_language_list(site_id=site.pk)
else:
languages = get_public_languages(site_id=site.pk)
language_info = []
for language in languages:
obj = get_language_object(language, site_id=site.pk)
languages_info.append({"code": obj['code'], "name": obj['name']})
context['languages'] = languages_info
context['current_language'] = get_language()
return context
With this context processor in place, you'll be able to access those context variables in your template and loop over them to create your link tags with the respective hreflang.
I am implement a simple form with Colander and Deform; however, I wish to override the default stylsheet and provide my own. However, I have no idea on how to provide my own styling for the form. Here is the code that I am using:
class Mapping(colander.Schema):
Firstname = colander.SchemaNode(colander.String(), css_class='deform-widget-with-style')
Lastname = colander.SchemaNode(colander.String(), css_class='deform-widget-with-style')
Email = colander.SchemaNode(colander.String(), css_class='deform-widget-with-style')
date = colander.SchemaNode(colander.Date(), widget = deform.widget.DatePartsWidget(), description = "content date")
class Schema(colander.Schema):
Age = colander.SchemaNode(colander.Integer(), css_class='deform-widget-with-style')
Firstname = colander.SchemaNode(colander.String(), css_class='deform-widget-with-style')
Lastname = colander.SchemaNode(colander.String(), css_class='deform-widget-with-style')
Email = colander.SchemaNode(colander.String(), css_class='deform-widget-with-style')
form = deform.Form(topList(),buttons=('submit',)).render(controlData)
When I run this, I get a plan, default user form. How can I provide my own templates with styling for the button and input boxes? Any suggestions or answers are greatly appreciated.
Current form:
Desired input field style:
Desired button style:
Your desired input field and submit button look like Bootstrap styles.
I would add bootstrap to your package and then add the appropriate class names, which will add some default styling: In your Paste Deploy configuration file (e.g. development.ini) add deform_bootstrap to the list of pyramid_includes, or add a this line if a pyramid.includes setting does not exist:
[app:main]
...
pyramid.includes = deform_bootstrap
This will put the templates in deform_bootstrap/templates into the deform search path.
Your input should look like
<input class="form-control">
And your button should look like
<button type="button" class="btn btn-primary"></button>
A typical deform example application instructs pyramid to serve static assets, such as JavaScript and CSS files. The application registers deform package assets using config.add_static_view()
def main(global_config, **settings):
"""pserve entry point"""
session_factory = UnencryptedCookieSessionFactoryConfig('seekrit!')
config = Configurator(settings=settings, session_factory=session_factory)
config.include('pyramid_chameleon')
deform.renderer.configure_zpt_renderer()
config.add_static_view('static_deform', 'deform:static')
config.add_route('mini_example', path='/')
config.add_view(mini_example, route_name="mini_example", renderer="templates/mini.pt")
return config.make_wsgi_app()
A template rendering a form can refer to the JS/CSS assets provided by deform in head tag. This is basically everything you need to run a deform application with default styling.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Deform Sample Form App</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- JavaScript -->
<script src="static/scripts/jquery-2.0.3.min.js"></script>
<script src="static/scripts/bootstrap.min.js"></script>
<tal:loop tal:repeat="js_resource js">
<script src="${request.static_path(js_resource)}"></script>
</tal:loop>
<!-- CSS -->
<link rel="stylesheet" href="static/css/bootstrap.min.css"
type="text/css">
<link rel="stylesheet" href="static/css/form.css" type="text/css">
<tal:loop tal:repeat="css_resource css">
<link rel="stylesheet" href="${request.static_path(css_resource)}"
type="text/css">
</tal:loop>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Sample Form</h1>
<span tal:replace="structure form"/>
</div>
</div>
</div>
</body>
</html>
A good customization approach would be to override any CSS classes provided by Bootstrap or add your own CSS in your custom application package mypyramidapp. Add CSS and/or JS assets to static or scripts folders - common folders in pyramid applications. You have to register these assets to your pyramid application.
config.add_static_view('static_myapp', 'myapp:static')
config.add_static_view('scripts_myapp', 'myapp:scripts')
Given that you can include your custom CSS files in any template and use common theming approaches to render forms in your custom styles.
I think overriding CSS would be more convinient to start with since you have to pass custom CSS classes to deform widgets using css_class parameter.
I recommend you to refer to these deformdemo example apps - a larger and a mini example to demo deform features and required pyramid application setup.
I'm new to Django, and facing issues rendering bootstrap on a django page.
This is my base html,
{% load staticfiles %}
<!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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Dropbox Web App Prototype</title>
<!-- Bootstrap -->
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="jumbotron">
<h1>Hello, world!</h1>
<p>This is a template showcasing the optional theme stylesheet included in Bootstrap. Use it as a starting point to create something more unique by building on or modifying it.</p>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script>
</body>
</html>
The static file is at the same level as the project directory and has the following structure,
I've also added the following line, to my settings.py file
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
The CSS is not rendering on the home page. Any help appreciated.
You are using an older syntax that's probably doesn't match your version of Django.
In your html file change:
{% load staticfiles %}
to
{% load static %}
Also, replace the single quote with a double quote :
"{% static 'bootstrap/css/bootstrap.min.css' %}"
to:
"{% static "bootstrap/css/bootstrap.min.css" %}"
you can see the exact syntax of dealing with static files here
BASE_DIR is defined by default to:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
Here __file__ is actually settings.py, so BASE_DIR is on the parent directory, the one that contains manage.py.
It seems your static folder is on another level, so just move it to the same level as manage.py and it should work.
CDN:
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
Static
In urls for django runserver:
if settings.DEBUG:
urlpatterns += [url(r'^static/(?P<path>.*)$', views.serve),]
When running from the webserver, you need to config an alias. Nginx example:
location /static {
alias /home/username/mysite/static;}
settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
In the html
replace this
<link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
with this
<link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
and check this is in the settings.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
just define additioaly static url in your settings as follow somewhere on the bottom:
STATIC_URL = '/static/'
and check again if your bootstrap is served
can you paste your BASE_DIR ? Can you set it to: BASE_DIR to BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
I am a beginner in Python and Django and I have been struggling with the following problem:
On localhost:8000/ webiste is beautiful and working fine but on localhost:8000/invoice/ SOME references are not working. CSS for example does not work but images and JavaScript do.
I am using relative links to point out where my path is.
<script src="{% static "js/jquery.min.js" %}"></script>
<script src="{% static "js/skel.min.js" %}"></script>
<script src="{% static "js/skel-layers.min.js" %}"></script>
<script src="{% static "js/init.js" %}"></script>
<noscript>
<link rel="stylesheet" href="{% static "css/skel.css" %}"/>
<link rel="stylesheet" href="{% static "css/style.css" %}"/>
<link rel="stylesheet" href="{% static "css/style-xlarge.css" %}"/>
</noscript>
<img src="{% static "images/pic07.jpg" %}" alt="" />
Settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static/"),
)
View.py
def home(request):
return render(request, 'principal.html',)
def invoice(request):
return render(request, 'invoice.html',)
When I check the page code with the browser I see the links are being referred as http://localhost:8000/invoice/static/css/somecss.css.
invoice.html is inside /project/folder/templates/ and my .css is inside /project/static/css/. invoice.html is inside the same folder my index.html (principal.html) page, which is working is.
Also, all links inside website/invoice/ page become website/invoice/link instead of website/link
Problem has been resolved removing tag. Also for 404 errors on console due to js files referencing other css files, I added a variable to my template to include the url:
<script>
var url = "{% static 'css/' %}";
</script>
And inside .js I used url.concat('style.css')
I have a beginner question with URL Dispatch or Traversal. What I am trying to do, is use Mako renderer to render my views. So I have this folder /includes/ where all the html and css and javascript is. Here is my Pyramid main code:
from pyramid.config import Configurator
def main(global_config, **settings):
config = Configurator(settings=settings)
config.add_static_view('includes', 'includes', cache_max_age=3600)
config.add_renderer(".html", "pyramid.mako_templating.renderer_factory")
config.add_route('home', '/')
config.scan()
return config.make_wsgi_app()
And these are my views:
#view_config(route_name='home', renderer='index.html')
def my_view(request):
return {'name':'Netherdrake'}
#view_config(name = 'login', renderer='login.html')
def login(request):
return {'name':'Netherdrake'}
The problem is, when I access ip:port/login the site works fine, but when I try ip:port/login/ the css, javascript and images don't work. The reason is, my absolute paths become invalid.
And here is my login.html snippet (which is mako template really) while login without /:
<link href="includes/css/twitter/bootstrap.css" rel="stylesheet">
<link href="includes/css/base.css" rel="stylesheet">
<link href="includes/css/twitter/responsive.css" rel="stylesheet">
<link href="includes/css/jquery-ui-1.8.23.custom.css" rel="stylesheet">
<script src="includes/js/plugins/modernizr.custom.32549.js"></script>
And here it is while Im going for login/ path (site is broken in this case, no css, images, js...):
<link href="includes/css/twitter/bootstrap.css" rel="stylesheet">
<link href="includes/css/base.css" rel="stylesheet">
<link href="includes/css/twitter/responsive.css" rel="stylesheet">
<link href="includes/css/jquery-ui-1.8.23.custom.css" rel="stylesheet">
<script src="includes/js/plugins/modernizr.custom.32549.js"></script>
The login.html is in /includes too.
How can I fix this, and make it work under both paths, with and without slash? I tried traveral and url dispatch, and problem is same in both.
All your hrefs should begin with an initial slash.