title: How to render a template with dynamic CSS?
body: <p>I want to create a dynamic CSS file in a view and then render a template which loads that CSS file. Depending on the arguments given to the view, the CSS may have different values at certain places every time the view is called. How would I go about doing that? (I should add that I have no experience with writing files in Python/Django.)</p>
  
  <p>Here is a simplified example of how I think it should work:</p>
  
  <pre><code># urls.py
  urlpatterns = patterns('',
      (r'^myview/(?P&lt;color&gt;[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 %}
      &lt;link rel="stylesheet" media="screen" href="{{ f.name }}" /&gt;
  {% endblock %}
  </code></pre>
  
  <p>For some reason, that doesn't work, although in the resulting HTML page's source code, it looks like the CSS file is loaded correctly. The <code>f</code> even arrives at the template correctly, because I can see its contents when I change the <code>&lt;link&gt;...</code> line to </p>
  
  <pre><code>&lt;link rel="stylesheet" media="screen" href="{{ f }}" /&gt;
  </code></pre>
  
  <p>(<code>f</code>instead of <code>f.name</code>). But the HTML is rendered without the desired color setting. Can anybody tell my why that is? </p>
  
  <p>I suspected some path issue, and I toyed around quite a bit with different paths, but to no avail.</p>
  
  <p>Please do not advise me to prepare several hardcoded CSS files (as I have found in answers to similar questions), because there will be several hundred possibilities.</p>