Migrate url tags to django 1.5
Asked Answered
F

2

24

I'm trying to migrate an old django application to django 1.5, There are 745 urls in different html files as this way:

{% url url_name %}

If I'm not wrong, this was deprecated and can't be used anymore from django 1.5 (as said here), and I have to transform all of them into:

{% url 'url_name' %}

Any idea to do this without going crazy? Maybe, some kind of script, I dont know... I can't imagine a way to do it with replace in path.

I'm probably missing something obvious.

Francesco answered 27/11, 2012 at 18:29 Comment(0)
B
39

NOTE: This command is destructive. Use version control or backup your templates directory before running it.

You can use sed. From your template directory (or directories) run

sed -i -r -e "s#\{% url ([a-zA-Z0-9_.:-]+)#\{% url '\1'#g" *

The expression matches {% url [view name], so arguments provided to the url template tag will be unaffected/unchanged.

To run it recursively,

find . -type f -print0 | xargs -0 sed -i -r -e "s#\{% url ([a-zA-Z0-9_.:-]+)#\{% url '\1'#g"

This sed command assumes your view names only contain alphanumerics, colons, dashes, periods and underscores - no other special characters. Now supports namespaced views.

Tested against the tags in this Django 1.4 url template tag Gist

Bunnie answered 27/11, 2012 at 20:48 Comment(6)
I can't seem to get this to work. It's touched all the files but made no changes.. Any ideas?Ilan
Oli's edit changed * to + which requires the -r flag for extended regex (on my computer at least). I've updated the answer above.Bunnie
this does not work, it will turn {% url app:name %} into {% url 'app':name %}. Fix: [a-zA-Z0-9_.:-]Ardrey
@dtc ...ok... You need to be more specific. Does find . -type f print a list of all the template files in the folder and subfolders you run it from? Do all your template tags follow the same patterns as the tags in the linked gist?Bunnie
Under MacOS, the FreeBSD sed syntax differs. Replace -r with -E, and -i requires a suffix argument, which can be an empty string -- e.g. sed -i '' -E -e ...Juanitajuanne
It may be better to use something like {%\s+url\s+ as {%url login %} is still valid but would be missed by this command. [where \s is white space and + 'is one or more'] Although, apparently some sed don't support \s.Smectic
O
2

There is also a snippet with a solution in python at http://djangosnippets.org/snippets/2905/

Just a warning, the find . -type f -print0 will find files that are "hidden" like files in your .git/ or .hg/ directories and may corrupt your repository or other binary files.

If you use the usual convention in django with your template files ending in .html, you can search more cautiously with:

find . -iname '*.html' -type f -print > file.list

examine file.list first to check which files are being modified before putting it together with the sed command

Odericus answered 27/9, 2013 at 6:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.