How to reverse/name urls with TemplateView.as_view? - django

I'm trying to use TemplateView.as_view() in urls.py then name it using ye olde templatetag url. Should this work? Or am I just doing it wrong..? Or is it some of the legacy crap in my app interfering? I've got...
<li>Terms and Conditions</li>
and
url(r'^legal/$', TemplateView.as_view(template_name="legal.html"), name="legal"),
Which yields
NoReverseMatch at /how-it-works/
Reverse for '"legal"' with arguments '()' and keyword arguments '{}' not found.
Seems to me this ain't ever gonna work this way.
How do we reverse urls with TemplateView?

The code you have posted is syntactically correct, but there is something else interfering.
That url tag is Django 1.5+ syntax (note the warning in the docs here), can you confirm that is the install you are using? I suspect this is the the problem, the double quoting of legal in the exception message is very suspicious. A Django 1.5+ exception message would contain 'legal', not '"legal"' for a URL that is not found by the dispatcher.
Is the url being registered by the URL dispatcher? You can tell in debug mode by hitting a bad URL (ie 404), the output will list all valid url paths from your URLConf.
Add more info if you continue to have problems so we can isolate further.
Good luck!

Related

Django urlconf fails to resolve valid regex

I'm experiencing problems in routing urls to views in Django. Specifically, I use URLs with the pattern:
url(r'^(?P<id>[A-Za-z0-9\ ]+)/(?P<subid>[A-Za-z0-9\ ]+)/managetables$', views.compiledata, name='compiledata')
An example url would be My data/current/managetables. I checked that the regex returns the expected captured groups on www.pyregex.com (example)
However, actually visiting the url does not result in the view being called. Most importantly though, it works for a highly similar url:
url(r'^(?P<id>[A-Za-z0-9\ ]+)/(?P<subid>[A-Za-z0-9\ ]+)/managetab$', views.compiledata, name='compiledata')
If I visit My data/current/managetab the view is called as expected. Additionally, appending a "/" in the urlconf works also - but it is not clear to me why, i.e.:
url(r'^(?P<id>[A-Za-z0-9\ ]+)/(?P<subid>[A-Za-z0-9\ ]+)/managetables/$', views.compiledata, name='compiledata')
and visiting My data/current/managetablesresults in a redirect to My data/current/managetables/which calls the view.
I appreciate any hints how to solve this issue.
Ok, whereas the problem did manifest only on one of two machines, the hint to slugify the urls solved the issue. For anybody encountering similar issues, more information on slugify can be found here:
Tango with Django's Chapter 7, as well as in the Django Documentation.

URL.py in Django unexpected behaviour

I've configured url.py as is explained in different places of the Django documentation, but its behaviour is completely anomalous, between consecutives acceses. In Debug Mode and after looking for an url I get the "Page not found" error. The strange thing is that between acceses the error given is different:
... Django tried these URL patterns, in this order:
^admin/?$
^cheqsim/?$
^login/?$
^logout/?$
^questions/?$
But if I look at url.py my last element is ^searchquestions/?$ and I had restarted the server before looking at it, but the error is indicating me a different urlpattern from the actual in url.py.
Then I keep looking URLs and when I delete all the cookies and I try some non-existent URL I get the actual URL.py:
, Django tried these URL patterns, in this order:
^login/?$
^logout/?$
^admin/?$
^cheqsim/?$
^searchquestions/?$
Ok, so now I try http://mysite.com/myprojecturl/searchquestions/ and voila! It appears a new pattern error that leave me completely knock out:
, Django tried these URL patterns, in this order:
^admin/?$
^cheqsim/?$
^login/?$
^logout/?$
A pattern that I had used like 5 or 6 hours ago!!!
Please, do anybody have any idea of what is happening to me because this is really frustrating...
Thank you very much
P.S.: By the way, some URLs matches sometimes magicly
Check if you have multiple runserver instances running.
Check the ROOT_URLCONF setting
It seems the solution is changing the project.wsgi file and is well explained here: http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html
Anyway only time will know... xD

Django URLs not matching with GET variables

I have the following django URL:
url(r'^companies/$', 'companies', name='companies'),
If I go to http://localhost:8000/companies/ it works perfectly. However, if I try adding any GET variables to the URL django raises a 404. For example, if I go to http://localhost:8000/companies/?c=1 django raises a 404. What's strange, is that on the 404 it says:
The current URL, companies/, didn't match any of these.
Why am I not able to pass GET variables to my URLs?
I am using django 1.4.
The companies view is defined like:
def companies(request):
It shouldn't have to accept any additional parameters because they are GET variables, not URL parameters- correct? I swear I've done this hundreds of times and it always just works...
Okay. Figured out what was causing this very strange behavior. I have a custom context processor that is calling resolve(request.get_full_path()). Apparently that causes a 404 if there are any GET variables in the URL. Very strange.

Installed Django app (registration) not using main urls.py for tests

I'm not sure if this is a bug with django-registration or what I'm doing.
I have a bare minimum project, with django-registration installed and no apps of my own. Django-registration requires a few templates, so I have them in templates/registration. In each template, I have a template tag {% url index %}, which is included in my urls.py.
By running ./manage.py test registration --failfast, I get:
TemplateSyntaxError: Caught NoReverseMatch while rendering: Reverse for 'index' with arguments '()' and keyword arguments '{}' not found.
My own template isn't seeing my url entry.
I debugged into Django's reverse function, and it seems as though my urls.py isn't being used at all. Instead registration.tests.urls.py is used.
Is this the intended behavior? I'm hoping not, since I can't get basic tests to pass. How do I get around this?
This is a bug in django-registration. This blog article describes the problem and a workaround.

Django's Satchmo and flatpages issue

I'm having a problem with configuring Flatpages in Satchmo. I've used them before, in a pure django app, but now it just doesn't work, returning 301 http error when I'm trying to enter a flatpage-configured site.
What I've done to configure it:
added the middleware "django.contrib.flatpages.middleware.FlatpageFallbackMiddleware" to MIDDLEWARE_CLASSES as last in the list,
configured example pages in admin module.
Simply what the docs say about flatpages config.
I'm feeling helpless. Don't know how could I debug this issue. Any thoughts on that?
And of course help appreciated.
Thanks to suggestion by Peter I've managed to narrow the problem to my urls.py file, for the satchmo shop.
The urlpatterns has only one entry:
(r'', 'django.views.generic.simple.redirect_to', {'url' : '/shop/'}),
This version does not work and moreover interfere with flatpages. But disabling flatpages from MIDDLEWARE_CLASSES and adding it to urls.py like the snippet below works:
(r'^(?P<url>.*)$', 'django.contrib.flatpages.views.flatpage'),
(r'', 'django.views.generic.simple.redirect_to', {'url' : '/shop/'}),
However next problem is with the redirection from / to /shop/. With the above config it results in infinite loop.
Perhaps you know the reason for that behavior (redirect overriding flatpage) and maybe You could suggest some working solution to this problem or what should be done with requests to /.
It returns 301? That's Page Moved Permanently (HttpResponsePermanentRedirect) and there are no references to that in the flatpages directory so I don't think it's coming from there. In fact there are only about 5 references to HttpResponsePermanentRedirect in all of the standard 1.1.1 release.
Possible approaches:
Comment out the FlatPages middleware and see if the error changes (I'm betting it won't).
Try changing the order of your MIDDLEWARE classes and see if things change.
When presenting a problem like this it's better to get very specific by showing the exact code from applicable portions of settings.py (or whatever) and by giving other things like precise URLs and the urls.py patterns you are trying to match.
Update:
OK, some random thoughts:
The pattern (r'^(?P<url>.*)$', 'django.contrib.flatpages.views.flatpage'), will match anything. Any patterns after it will never be seen.
flatpages doesn't work by being called directly, it does its magic in middleware. It looks for 404 responses (Page Not Found) and then looks to see if that path exists in its table. If so, it calls a view that renders the page, etc. etc. If it doesn't find a match it let's the 404 continue on through middleware processing.
The pattern (r'', 'django.views.generic.simple.redirect_to', {'url' : '/shop/'}), will match anything (I just tested it). If you want to match an empty path, use r('^$', etc.). This is the source of your infinite loop.
If you are new to regular expressions the Django urls.py file can seem like F*cking Magic. I recommend starting very simply and add one rule at a time. Do some quick tests to ensure that the new rule a) matches stuff you want it to match, and b) doesn't match stuff it shouldn't. In particular, make sure that some of the rules that occur later in the file are still reachable. In this case they wouldn't have been which should have raised a red flag.