ViewDoesNotExist while rendering - django

I have split up views.py into two files, organized thus:
views/
__init__.py
public.py
private.py
In one view (in public) I render a template which has the following:
<a href='{% url app.views.private.login_view %}'>Login</a>
I get the following error when loading the url:
TemplateSyntaxError at /
Caught ViewDoesNotExist while rendering:
Could not import app.views.private.app.views. Error was: No module
named app.views
What am I doing wrong?

Try naming your url and then using that name inside the {% url ... %} tag, like so:
#urls.py
url(r'^xyz/abc/$','app.views.private.login_view', name='login_view'),
#login_view.html (template-code)
<a href='{% url login_view %}'>Login</a>

I would recommend naming your url patterns, then using the name in the {% url %} tag.

Are you using {% load url from future %} ? If so you will need to put quotes around your url so that it is {% url 'app.views.private.login_view' %}
The release notes for Django 1.3 explains it.
https://docs.djangoproject.com/en/dev/releases/1.3/#changes-to-url-and-ssi

Related

django templates url parse error

I am trying to construct a URL in the template as shown but it ends up getting the following error. What am I doing wrong here?
EDIT:
'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs.
urls.py
url(r'^launch$', views.LaunchInstanceView.as_view(), name='launch')
templates :
<a href="{%url launch %}" >Launch</a>
I've also tried
urls.py
url(r'^launch$', views.LaunchInstanceView.as_view(), name='instance.views.launch')
templates :
<a href="{%url instances.views.launch %}" >Launch</a>
Edit 1:
with quotes get the error as
<a href="{%url 'launch' %}" >Launch</a>
Reverse for 'launch' with arguments '()' and keyword arguments '{}' not found.
urls.py
urlpatterns = patterns(VIEW_MOD,
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^launch$', views.LaunchInstanceView.as_view(), name='launch'),
url(r'^(?P<instance_id>[^/]+)/$',
views.DetailView.as_view(), name='detail'),
)
views.py
class LaunchInstanceView(workflows.WorkflowView):
workflow_class = project_workflows.LaunchInstance
def get_initial(self):
initial = super(LaunchInstanceView, self).get_initial()
initial['project_id'] = self.request.user.tenant_id
initial['user_id'] = self.request.user.id
return initial
It should be:
<a href="{% url 'launch' %}" >Launch</a>
You should provide name as 'launch' is your url.
Please edit that if you want to call url like <a href="{%url 'launch' %}" >Launch</a>
url(r'^launch$', views.LaunchInstanceView.as_view(), name='launch')
if i am getting wrong. Please update your question so i can understand your problem easily.
If the above provied urls.py is you ROOT_URLCONF.. then following should work:
url(r'^launch/$', views.LaunchInstanceView.as_view(), name='launch') #Its a good practice to put '/' at the end of the pattern name, so if someone enters a '/' at the end in the browser it doesn't give 404
and
<a href="{% url 'launch' %}" >Launch</a>
Otherwise
Please check your settings.py file and See, to which file ROOT_URLCONF points to.
if it is different and you are including the above urls.py in the root urls.py file, then please check if it is either being included using a namespace e.g
url(r'^xyz/', include('path_to_above_urls.py', namespace='abc')),
or there's some other url with same name in root urls.py e.g:
url(r'some_pattern$', someview.as_view(), name='launch'),
url(r'^xyz/', include('path_to_above_urls.py')),
In 1st case you will have to access the url with {% url 'abc:launch' %}
In 2nd case you will have to change the name to make it unique.

Django NoReverseMatch

I have the following setup:
/landing_pages
views.py
urls.py
In urls.py I have the following which works when I try to access /competition:
from django.conf.urls.defaults import *
from django.conf import settings
from django.views.generic.simple import direct_to_template
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^competition$', 'landing_pages.views.page', {'page_name': 'competition'}, name="competition_landing"),
)
My views.py has something like this:
def page(request, page_name):
return HttpResponse('ok')
Then in a template I'm trying to do this:
{% load url from future %}
<a href="{% url 'landing_pages.views.page' page_name='competition'%}">
Competition
</a>
Which I apparently can't do:
Caught NoReverseMatch while rendering: Reverse for 'landing_pages.views.page' with arguments '()' and keyword arguments '{'page_name': u'competition'}' not found.
What am I doing wrong?
You ask in your comment to DrTyrsa why you can't use args or kwargs. Just think about it for a moment. The {% url %} tag outputs - as the name implies - an actual URL which the user can click on. But you've provided no space in the URL pattern for the arguments. Where would they go? What would the URL look like? How would it work?
If you want to allow the user to specify arguments to your view, you have to provide a URL pattern with a space for those arguments to go.
{% url [project_name].landing_pages.views.page page_name='competition' %}
Or better
{% url competition_landing 'competition' %}

NoReverseMatch Error

I keep getting this error for the django login system. Here is part of my urls.py:
(r'^contractManagement/login', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
The exact error I am getting:
Exception Type: NoReverseMatch
Exception Value: Reverse for ''django.contrib.auth.views.login'' with arguments '()' and keyword arguments '{}' not found.
I can't understand why i am getting this error. If you need anything else let me know.
You don't show where you are trying to reverse this URL, but it looks like you have double-quoted it. If you're using the url tag, note that you don't need quotes around the url name:
{% url django.contrib.auth.views.login %}
not
{% url 'django.contrib.auth.views.login' %}
You see that ''the.unknown.view'' is reported including too many qoutes.
It is because the quoted syntax will be valid in Django 1.5 and higher. For Django 1.3 or 1.4, you should activate the future behavior by this line in the template:
{% load url from future %}
which is valid also for Django 1.5.
Example for Django 1.5+
{% url "path.to.some.view" %}
Classic syntax for Django <= 1.4.x (without "future" command) is:
{% url path.to.some.view %}
I would give your url a name (in order to do that, you need to use the url method) Also you should add a trailing slash to all your urls, cause the django CommonMiddleware is going to be doing a 302 redirect on all your urls if you don't:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
url(r'^contractManagement/login/', 'django.contrib.auth.views.login', {'template_name': 'login.html'}, name='contract_login'),
)
Then you can use reverse in your code, or url in your templates, and if you ever decide to change the actual url (ie: changedCotractManagement/login/), as long as the name is the same, your code will still be good.
in code:
from django.core.urlresolvers import reverse
reverse('contract_login')
in template:
{% url contract_login %}
Edit: per MrOodles

Is it possible to pass query parameters via Django's {% url %} template tag?

I'd like to add request parameters to a {% url %} tag, like ?office=foobar.
Is this possible? I can't find anything on it.
No, because the GET parameters are not part of the URL.
Simply add them to the end:
<a href="{% url myview %}?office=foobar">
For Django 1.5+
<a href="{% url 'myview' %}?office=foobar">
A way to mix-up current parameters with new one:
{% url 'order_list' %}?office=foobar&{{ request.GET.urlencode }}
Modify your settings to have request variable:
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
TEMPLATE_CONTEXT_PROCESSORS = TCP + (
'django.core.context_processors.request',
)
Use urlencode if the argument is a variable
<a href="{% url 'myview' %}?office={{ some_var | urlencode }}">
or else special characters like spaces might break your URL.
Documentation: https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#urlencode
First, a silly answer:
{% url my-view-name %}?office=foobar
A serious anwser: No, you can't. Django's URL resolver matches only the path part of the URL, thus the {% url %} tag can only reverse that part of URL.
If your url (and the view) contains variable office then you can pass it like this:
{% url 'some-url-name' foobar %}
or like this, if you have more than one parameter:
{% url 'some-url-name' office='foobar' %}
Documentation: https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#url
Tried all the above, nothing worked.
My system has:
Python 3.8.10
python3 -m django --version 4.0.3
Here's what worked for me:
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('single/', views.single, name='single'),
]
views.py
def single(request):
url = request.GET.get('url')
return HttpResponse(url)
Calling from .html file
<a href={% url 'single' %}?url={{url}} target="_self">
Broswer URL
http://127.0.0.1:8000/newsblog/single/?url=https://www.cnn.com/2022/08/16/politics/liz-cheney-wyoming-alaska-primaries/index.html
Try this:
{% url 'myview' office=foobar %}
It worked for me. It basically does a reverse on that link and applies the given arguments.

Django 0.96 and url

I want to get the absolute url of a given action in Django 0.96 (using Google App Engine).
I have this url configuration:
from django.conf.urls.defaults import patterns
urlpatterns = patterns('framework.facebook',(r'^canvas/invite_friends$','views.inviteFriends'),
)
In my template:
window._url = '{% url views.inviteFriends %}';
I don't understand why this doesn't work.
Syntax for url is package.package.module.function args so if you replace 'views' with your module/ application name it should work.
{% url app_name.inviteFriends %}
An example:
If the full path to your function is myproject.myapp.views.inviteFriends code would be:
{% url myapp.inviteFriends %}
or
{% url myproject.myapp.inviteFriends %}