Login

Upgrade django url tags

Author:
Craterdome
Posted:
March 29, 2013
Language:
Python
Version:
1.5
Tags:
tag url upgrade
Score:
1 (after 1 ratings)

In Django 1.5 url tags require you to pass in the name of the url as a string.

So where you used to be able to do this {% url home_page %} you now have to do this {% url 'home_page' %}

Upgrading an old project can be a pain, so here is a snippet for a py file that will update all your url tags. Just put it in a py file in your root directory and execute it.

The error you get otherwise is: 'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import os, re

app_path = os.path.split(os.path.split(__file__)[0])[0]
PROJECT_ROOT = os.path.abspath(app_path)

def update_path(directory):
	"Update {% url to include ''"
	for path, dirs, files in os.walk(directory):
		for fname in files:
			if fname.endswith('.txt') or fname.endswith('.html'):
				fpath = os.path.join(path, fname)
				with open(fpath) as f:
					s = f.read()
				s = re.sub(r'{% url "(\w+)" ', r"{% url '\1' ", s)
				s = re.sub(r'{% url (\w+) ', r"{% url '\1' ", s)
				with open(fpath, "w") as f:
					f.write(s)
		for dir in dirs:
			update_path(dir)
update_path(PROJECT_ROOT)

More like this

  1. Variable resolving URL template tag by UloPe 6 years ago
  2. Unobtrusive comment moderation by ubernostrum 8 years ago
  3. Template tag to create mailto links with options by celopes 5 years, 9 months ago
  4. backupdb command by msaelices 6 years, 9 months ago
  5. Use email addresses for user name by chris 8 years, 1 month ago

Comments

Please login first before commenting.