Can i switch of <link href=""> using django? - django

is that possible to make a switch button that change my styleesheet using django framework ?
'''
By example, in my head html i got this :
<link href="{% static 'website/assets/css/style_dark.css' %}" rel="stylesheet">
And i would like to get the bellow stylesheet IF my button ( on the body html is clicked )
<link href="{% static 'website/assets/css/style_light.css' %}" rel="stylesheet">
'''

Without reloading page it won't work. (Because Django puts those things during rendering the page).
Another way around you can add on button click some URL with parameter (e.g. <a href="/?style={{ style }}">) which will lead to the same view.
So in Django, when view was called with this parameter - you do the trick:
def my_view(request):
style = request.GET.get('style')
if style == 'dark':
context['style'] == 'light'
elif style == 'light':
context['style'] == 'dark'
return HttpResponse(loader.get_template('template.html').render(context, request))
and in template:
<link href="{% static 'website/assets/css/style_{{ style }}.css' %}" rel="stylesheet">
Though, it is kind of a work-around. (Better to do such things in front-end). But in general, it should do the trick.

Related

add filter_horizontal into a model form in django [duplicate]

I have a non-admin form in which I'd like to use filter_horizontal on. I have read this which does much more than what I want (I only want the filter_horizontal). I wanted to check to see if anyone has come up with a simpler (more current) way to just implement the filter_horizontal.
So here is the code:
class County(models.Model):
"""County Names"""
name = models.CharField(max_length=64)
state = USStateField(null=True)
class Company(models.Model):
"""The basics of a company"""
name = models.CharField(max_length = 100)
counties = models.ManyToManyField(County,blank=True, null=True)
Then our form currently look like this. I thought this would work..
from django.contrib.admin.widgets import FilteredSelectMultiple
class RaterCompanyForm(ModelForm):
class Meta:
model = RaterOrganization
exclude = ('remrate_projects',)
widgets = {'counties': FilteredSelectMultiple(verbose_name="Counties",
is_stacked=True,) }
class Media:
css = {'all':['admin/css/widgets.css']}
js = ['/admin/jsi18n/']
BTW: I understand this may be a duplicate of this but his question wasn't answered. I've done plenty of homework here and here but neither of these appear to work.
I know this thread is old, but hopefully this info will help someone else who stumbles upon this page like I did.
After much pain and suffering, I was able to get this to work with Django 1.4. Like rh0dium, I tried all those articles, but had to make a lot of tweaks.
You don't have to do anything special with the ModelForm, but you do have to include all these js and css files in the template:
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/core.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.init.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/SelectFilter2.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/SelectBox.js"></script>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/widgets.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/forms.css"/>
Then render the form as you normally would, but you need to get the fieldset elements and class names right for the css to work. For example:
<fieldset>
<div class="form-row">
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" value="submit">Add</button>
</form>
</div>
</fieldset>
Then at the BOTTOM of the template (after the markup to render the form), add this script and replace pricetags with whatever your Many to Many (M2M) relationship name is on the model form's model:
<script type="text/javascript">
addEvent(window, "load", function(e) { SelectFilter.init("id_pricetags", "pricetags", 0, "{{ STATIC_URL }}admin/"); });
</script>
Apparently your media location may be something different, but {{ STATIC_URL }}admin/ worked for me.
I got this working very easily in Django 3 in 2020; perhaps things have changed since the question was asked in 2011. All I needed to do was set the widget of the form field, no custom Media defined on the class (django will add it automatically based on the widgets used):
class FooForm(forms.Form):
linked_bars = forms.ModelMultipleChoiceField(queryset=Bar.objects.all(),
widget=widgets.FilteredSelectMultiple(Bar._meta.verbose_name_plural, False))
# end of class, no Media!
You DO need to have the jsi18n loaded globally so in a base template I have:
{% block extrahead %}
{{ block.super }}
<script type="text/javascript" src="/admin/jsi18n/"></script>
{% endblock %}

django how to set background colour in html based on context

I am trying to change the background colour in a django project based on some information sent via the context
body base {
}
body alert {
background-color: #FCFF33;
}
def check_alert() -> bool:
return ...
def index(request):
template = 'proj/index.html'
...
context['alert'] = check_alert()
return render(request, template, context)
How can I select the body class in the proj.html based on the field alert in
html looks like
{% load static %}
<html>
<link rel="stylesheet" href="{% static 'css/proj.css' %}" />
<body>
...
</body>
</html>
I am wondering there is a solution like
<html>
<link rel="stylesheet" href="{% static 'css/proj.css' %}" />
<body class={% alert %}>
...
and changing my view.py
context['alert'] = 'alert' if check_alert() else 'base'
EDIT:
When trying art06's solution, I realized that my template would not take any format for the body. Even If I dont class it and just have a simple css
body {
background-color: #FFD9D9;
}
Any suggestions why that is?
Other formats in that css for example for tables created via
{% render_table table%}
are implemented correctly based on the css content.
Css
body.alert{...}
body.base{...}
Template
<body class="{{alert}} ...
If you want to reference alert....Reference it like {{alert}} instead of {% alert %}.

django- how to address static files in 404.html template

according to django's documentation:
When you raise Http404 from within a view, Django loads a special view devoted to handling 404 errors. By default, it’s the view django.views.defaults.page_not_found(), which either produces a very simple “Not Found” message or loads and renders the template 404.html if you created it in your root template directory.
, i created a 404.html file in the root template directory.
when the app raises a 404 error, this 404.html that i created before, will shown, but it's css and it's background image not load.
this is the 404.html file code:
<!DOCTYPE html>{% load staticfiles %}
<html>
<head>
<title>not found</title>
<link rel="stylesheet" href="{% static 'css/error_style.css' %}"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
</head>
<body class="color-404">
<div id="error">
<img class="error-image" src="{% static 'img/404.jpg' %}"/>
</div>
<div class="error-router">
<i class="fa fa-home"></i>
<i class="fa fa-arrow-left"></i>
</div>
</body>
</html>
how can i fix this problem?
tanx
Not really an answer to your question, but in general it is best to not have external .js and .css files in error-pages.
Include it in the page itself, to avoid situations like this, where for some reason the error-page produces an error. Use a single static page.
I found what was the problem.
because i set DEBUG to False, django's built-in webserver, was not served staticfiles.

Whats easiest way to use filter_horizontal outside of the Admin in Django

I have a non-admin form in which I'd like to use filter_horizontal on. I have read this which does much more than what I want (I only want the filter_horizontal). I wanted to check to see if anyone has come up with a simpler (more current) way to just implement the filter_horizontal.
So here is the code:
class County(models.Model):
"""County Names"""
name = models.CharField(max_length=64)
state = USStateField(null=True)
class Company(models.Model):
"""The basics of a company"""
name = models.CharField(max_length = 100)
counties = models.ManyToManyField(County,blank=True, null=True)
Then our form currently look like this. I thought this would work..
from django.contrib.admin.widgets import FilteredSelectMultiple
class RaterCompanyForm(ModelForm):
class Meta:
model = RaterOrganization
exclude = ('remrate_projects',)
widgets = {'counties': FilteredSelectMultiple(verbose_name="Counties",
is_stacked=True,) }
class Media:
css = {'all':['admin/css/widgets.css']}
js = ['/admin/jsi18n/']
BTW: I understand this may be a duplicate of this but his question wasn't answered. I've done plenty of homework here and here but neither of these appear to work.
I know this thread is old, but hopefully this info will help someone else who stumbles upon this page like I did.
After much pain and suffering, I was able to get this to work with Django 1.4. Like rh0dium, I tried all those articles, but had to make a lot of tweaks.
You don't have to do anything special with the ModelForm, but you do have to include all these js and css files in the template:
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/core.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.min.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.init.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/SelectFilter2.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/SelectBox.js"></script>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/widgets.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/forms.css"/>
Then render the form as you normally would, but you need to get the fieldset elements and class names right for the css to work. For example:
<fieldset>
<div class="form-row">
<form method="post" action=".">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" value="submit">Add</button>
</form>
</div>
</fieldset>
Then at the BOTTOM of the template (after the markup to render the form), add this script and replace pricetags with whatever your Many to Many (M2M) relationship name is on the model form's model:
<script type="text/javascript">
addEvent(window, "load", function(e) { SelectFilter.init("id_pricetags", "pricetags", 0, "{{ STATIC_URL }}admin/"); });
</script>
Apparently your media location may be something different, but {{ STATIC_URL }}admin/ worked for me.
I got this working very easily in Django 3 in 2020; perhaps things have changed since the question was asked in 2011. All I needed to do was set the widget of the form field, no custom Media defined on the class (django will add it automatically based on the widgets used):
class FooForm(forms.Form):
linked_bars = forms.ModelMultipleChoiceField(queryset=Bar.objects.all(),
widget=widgets.FilteredSelectMultiple(Bar._meta.verbose_name_plural, False))
# end of class, no Media!
You DO need to have the jsi18n loaded globally so in a base template I have:
{% block extrahead %}
{{ block.super }}
<script type="text/javascript" src="/admin/jsi18n/"></script>
{% endblock %}

css pulling from the wrong location with {{ STATIC_URL }} on my form page only

I'm using django 1.3
I'm using a base.html template which my pages inherit from. Everything works fine except for one page (which has a form on it).
That page is trying to call the CSS from /links/addlink/css/site.css but this is the wrong location. It is in /static/css/site.css
In my base.html I have <link rel="stylesheet" href="{{ STATIC_URL }}css/site.css" type="text/css" charset="utf-8" />
If I create a completely seperate template and use the full path like <link rel="stylesheet" href="http://127.0.0.1:8000/static/css/site.css" type="text/css" charset="utf-8" /> then my page renders correctly.
What is wrong?
You are not using RequestContextin your view.
See here: Referring to static files in templates