Django Dynamic Formset JQuery Library

Django Dynamic Formset JQuery Library

I spent a while searching for a code snippet that would allow the user to dynamically add fields to a form. For instance, if you want to enter several individual items, but don’t know in advance how many…

The perfect snippet eventually led me to a full-fledged jQuery library, for Javascript over Django. Check it out!

Django Template Error – Reverse Template Not Found

Running into a strange django error:

“Reverse for ” with arguments ‘()’ and keyword arguments ‘{}’ not found. ”

This error appeared mysteriously when porting a working project from one computer to another. The first computer was running Python 2.7.1, the second – Python 2.7.2. All other project settings were identical.

For the original computer (Python 2.7.1), the following settings:
base.html:

<a href="{% url 'display_rulelist' %}"><span class="numbertxt"> Rule List </span>

urls.py:

url(r'^rulelist/$', rulelist.views.display_rulelist,  name = 'display_rulelist')

worked correctly, with no errors. These did NOT work for Python 2.7.2!

For the new computer (Python 2.7.2),
base.html:

<a href="{% url display_rulelist %}"><span class="numbertxt"> Rule List </span>

removing the apostrophes solved the problem.

I tried going back to the first version and removing the apostrophes as well, but after making the change – the first project no longer worked.

All I can recommend: when running into this error, try both versions!

EDITED:

It was pointed out to me (see comments below) that the url formatting was updated between django 1.4.x and django 1.5. I had completely overlooked that the django versions were different, but so they were: the first project had run django 1.5, and the second: django 1.4.3. Beware of old django versions, users-who-work-on-more than one computer! BEWAAAARE!

Adding CSS templates to Django – A Tutorial for Dummies

I have seen a lot of pages and stackoverflow questions that just want to know… how in hell do I get a CSS template to work with Django, even on a basic level? I found the official documentation for Django static files a bit confusing. So I’ve laid out the steps here, along with some basic tips. This will work for offline development scenarios – I haven’t deployed my project on a *real* server yet. 😉

Without further ado, here we go:

  1. The default location for your static files (CSS style sheets, images) is per app: for each app, create a static subdirectory, and put all your static files there. These apps need to be listed in your INSTALLED APPS setting.
  2. Place your statics files in the appropriate directory. Here the *.css files for app books are located in the static subdirectory, and the images are located in a dedicated images subdirectory within .
  3. Directory Structure

  4. Add django.contrib.staticfiles to your INSTALLED_APPS, in your settings.py file (if it isn’t there already).
  5. INSTALLED_APPS = (
        ...
        'django.contrib.staticfiles',
        'MyWebsite.books'
    )
    
  6. If necessary, add explicit local paths to STATICFILES_DIRS in settings.py
  7. # URL prefix for static files.
    # Example: "http://example.com/static/", "http://static.example.com/"
    STATIC_URL = '/static/'
    
    # Additional locations of static files
    STATICFILES_DIRS = (
        'C:/workspace/MyWebsite/src/MyWebsite/static',
        # Put strings here, like "/home/html/static" or "C:/www/django/static".
        # Always use forward slashes, even on Windows.
        # Don't forget to use absolute paths, not relative paths.
        )
    
  8. When you refer to the files in your templates, you will use the tag {{ STATIC_URL }}. Examples for a CSS stylesheet and an image:
  9. 
    Display Authors
        	<link href="{{ STATIC_URL }}style1.css" rel="stylesheet" type="text/css" />
    <img alt="" src="{{ STATIC_URL }}images/photo.jpg" />
    
    
  10. As shown above, CSS tags are placed below the title tag.
  11. This should work now. Good luck!

Django Book Tutorial doesn’t work – CSRF error

Hi,

If you’ve been working your way through the Django Book tutorial, you may have run into a spot of trouble with the form chapter. Even though I had basically cut and pasted in the chapter code, I kept getting a CSRF Verification Failed error, which was definitely not listed in the book.

We don't like this.

We don’t like this.

CSRF stands for Cross Site Request Forgery, which is a type of attack on your web page. This occurs when a malicious Web site contains a link, a form button or some javascript that is intended to perform some action on your Web site, using the credentials of a logged-in user who visits the malicious site in their browser. CSRF protection in Django is meant to prevent just that, which is why we get an error if we haven’t properly secured our forms. It seems to have been enforced in newer versions of Django, but still not updated in the online book.

The problem can be solved as follows:

  1. Add the middleware 'django.middleware.csrf.CsrfViewMiddleware' to your list of middleware classes, MIDDLEWARE_CLASSES.
  2. In any template that uses a POST form, use the csrf_token tag inside the html.
    <form action="" method="post">
        	{% csrf_token %}
            <table>
                {{ form.as_table }}
            </table>
            <input type="submit" value="Submit">
        </form>
    
  3.  Instead of using a context in your forms, use a RequestContext in views.py. The code looks like this:
from django.template import RequestContext
...
def contact(request):
    ...
    initialData = {'form': form}
    return render_to_response('contact_form.html', initialData,
          context_instance=RequestContext(request))

The RequestContext contains a CSRF token which is necessary to prevent this error. Completing these steps should resolve the problem! 🙂

Configuring PyDev in Eclipse to work with Django

The pre-requisite for working with Django is that it is installed in the Python interpreter you want to use.

Eclipse will add the Django options to the menu automatically. At this point, you can:

  1.  create a new Django project: Ctrl+N > PyDev Django Project
  2.  change an existing project to Django: right-click the project and choose
    PyDev -> Set as Django Project.
  3. (you can also change projects back in the same way).

In order to compile and run the web server, use the standard CTRL-F11.

  1. Don’t forget to add runserver to the Run Configuration
  2. Add –noreload as well so you can see the console output.

You can find a complete tutorial here.