I want to create a dynamic CSS file in a view, and then display a template that loads this CSS file. Depending on the arguments provided to the view, CSS may have different meanings in certain places each time the view is called. How can I do it? (I have to add that I have no experience writing files in Python / Django.)
Here is a simplified example of how I think it should work:
# urls.py urlpatterns = patterns('', (r'^myview/(?P<color>[0-9a-f]{6})/$', create_css_file), ) # views.py def create_css_file(request, color): raw = "@charset 'UTF-8';\n\n" raw += "body {\n" raw += " color: #" + color + ";\n" raw += "}\n\n" f = open('mydynamic.css', 'r+') f.write(raw) return render_to_response('mytemplate.html', locals()) # mytemplate.html {% extends "base.html" %} {% block head %} <link rel="stylesheet" media="screen" href="{{ f.name }}" /> {% endblock %}
For some reason, this does not work, although in the source code of the HTML page it looks like the CSS file is loaded correctly. f
even gets into the template correctly, because I can see its contents when I change the line <link>...
to
<link rel="stylesheet" media="screen" href="{{ f }}" />
( f
instead of f.name
). But HTML is displayed without the right color setting. Can someone tell me why this is so?
I suspected some kind of problem, and I played a little with different paths, but to no avail.
Please do not advise me to prepare some hard-coded CSS files (as I found in answers to similar questions), because there will be several hundred possibilities.
source share