Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing css styles from view in Django

Sorry in advance if there is an obvious answer to this, I'm still learning the ropes with Django.

I'm creating a website which has 6 pre determined subjects (not stored in DB) english, civics, literature, language, history, bible

each subject is going to be associated with a unique color.

I've got a template for a subject.html page and a view that loads from the url appname/subject/subjectname

what I need to do is apply particular css to style the page according to the subject accessed. for example if the user goes to appname/subject/english I want the page to be "themed" to english.

I hope I've made myself clear, also I would like to know if there is a way I can add actual css code to the stylesheet and not have to change attributes one by one from the back-end.

thanks very much!

like image 641
davegri Avatar asked Aug 31 '25 17:08

davegri


1 Answers

In templates you can use conditionals for add css, like this:

<div class="{% if subject=='civics' %}civic-class{% endif %}"></div>

For this, subject value should come from view. Now, for themed page, you could use the extends tag. Let's supose:

def your_view(request):
    subject  # Here you get the url subject, 'how' is up to you
    if subject == 'english'
        template_base = '/some/html/tenplate.html'
    elif subject == 'civis':
        template_base = '/some/other/template.html'
    ... # then you return 'template_base' variable to template

Then in template:

{% extends template_base %}  # at the top

Hope this helps, is the same logic if you use Class-Based views.

like image 86
Gocht Avatar answered Sep 02 '25 05:09

Gocht