Django NoReverseMatch error, reverse function not work with no arguments - python

this NoReverseMatch error is driving me nuts. I'm using Django 1.6 and I have checked through my urls and it just doesn't work. Please kindly guide me on this.
I basically want to do something deadly simple, just when I submit a html form, I get the data I want and then redirect to a result page, but it just doesn't work...
Here is my index.html file
<form name="input" action="{% url 'whatspring:sending' %}" method="post">
{% csrf_token %}
Recipient: <input type="text" name="usrname">
<br>
<input type="submit">
</form>
<br>
my view.py
def index(request):
return render(request,'springsend/index.html')
def sending(request):
var = request.POST['usrname']
doSomethinghere()
return HttpResponseRedirect(reverse('whatspring:results'))
def results(request):
return render(request,'springsend/send_results.html')
then my app urls.py
from django.conf.urls import patterns, url
from springsend import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^results/$', views.results, name='results'),
)
and the main urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^send/', include('springsend.urls', namespace="whatspring")),
)
I have tried to look into the problem and it seems that the reverse function cannot get the name for the reverse url that I want (i.e. 'results' under the namespace 'whatspring'....)Am I missing something something trival? Please kindly help.

Your urls.py (springsend one) doesn't seem to have a url for the sending view, that's probably why {% url 'whatspring:sending' %} can't find it.
Simply change it to
from django.conf.urls import patterns, url
from springsend import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^results/$', views.results, name='results'),
url(r'^sending/$', views.sending, name='sending'), # this line
)
Every accessible view needs a url. The user's browser needs to have some address to send things. If it would just send it to your domain without url, Django would have no way to tell which url is requested. Django does not auto-generate these urls (which is probably good).
(The user himself does not need to know this url; you don't need to place any ` links anywhere.)

Related

Page Not Found Error occured while trying to render form in django

I've been following the instructions here.
This is the error it gives me, when i try to run it on localhost:
Page not found (404)
Request Method: GET
Request URL: http://localhost:7000/account.html
Using the URLconf defined in gettingstarted.urls, Django tried these URL patterns, in this
order:
[name='index']
[name='account']
db/ [name='db']
admin/
^celery-progress/
The current path, account.html, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change
that to False, and Django will display a standard 404 page.
This is what i have in my urls.py
urlpatterns = [
path("", hello.views.index, name="index"),
path("", hello.views.account, name="account"),
path("db/", hello.views.db, name="db"),
path("admin/", admin.site.urls),
re_path(r'^celery-progress/', include('celery_progress.urls'))
]
This is what i have in views.py
def account(request):
if request.method == 'POST':
form = AccountForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('loading.html')
else:
form = Nameform()
return render(request, 'account.html', {'form': form})
Finally this is the form itself(account.html):
<form action="/account/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
I have the feeling i'm missing something really simple but i can't for the life of me see it. Any help would be greatly appreciated.
First, you need to change the URL patterns, because multiple views (hello.views.index and hello.views.account) are pointing towards the same pattern
urlpatterns = [
path("index/", hello.views.index, name="index"),
path("account/", hello.views.account, name="account"),
path("db/", hello.views.db, name="db"),
path("admin/", admin.site.urls),
re_path(r'^celery-progress/', include('celery_progress.urls'))
]
then, access the URL, http://localhost:7000/account/
You are requesting for the url that could match the string /account/ but in your urlpatterns variable you have an empty string so it can't match anything.
Remember that the first argument of urlpatterns is a pattern string that can be matched with regex.
Perhaps you could map it like:
path("/account/", hello.views.account, name="account")

NoReverseMatch error after upgrade Django version

I'm newbie in Django and i read many topic here and not found solution for my case. I believe it's easy, but i can't find the solution.
Basically i have the code in my urls.py and the works fine in Django 1.8.4:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^leds/', include('ledscontrol.urls')),
url(r'^', 'controli2c.view.view_home'),
]
My template file contains
{% url 'controli2c.views.view_home' as home_url%}
<a href="{% url 'controli2c.views.view_home' %}" {% if request.path == home_url %} class="active"{% endif %} >HOME</a>
When i update Django, i get the error "TypeError: view must be a callable or a list/tuple in the case of include()". Then, i change my urls.py code to:
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^leds/', include('ledscontrol.urls')),
url(r'^', 'views.view_home'),
]
Now, i have the NoReverseMatch when i open the browser (http://localhost:8000):
"Reverse for 'controli2c.view.view_home' not found. 'controli2c.views.view_home' is not a valid view function or pattern name."
In a post in the forum i found:
"The solution is to update your urls.py to include the view callable. This means that you have to import the view in your urls.py. If your URL patterns don't have names, then now is a good time to add one, because reversing with the dotted python path no longer works."
I believe that's my problem. But i don't know what changes i have to do.
Anyone can help me?
Thanks a lot!!
Now you have to pass a callable, so:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^leds/', include('ledscontrol.urls')),
url(r'^', views.view_home),
]
I think it might work now.
I found the solution!
To keep my template file with the same code, i have make these change
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^leds/', include('ledscontrol.urls')),
url(r'^', 'views.view_home',name='controli2c.views.view_home'),
]
Thanks!

Django URL error when using forms

I am fairly new to Django and I am totally stuck on what is causing this error. I have done lots of searching but to no avail! Any help would be super appreciated.
The actual form works fine but when I try and submit the input data I get the error:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^admin/
^$ [name='home']
^patientlist [name='patient_list']
^patientdetail/(?P<pk>\d+)/$ [name='patient_detail']
^add_patient/$ [name='add_patient']
The current URL, spirit3/add_patient/, didn't match any of these.
My urls.py in the mysite directory looks like:
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('spirit3.urls')),
]
My urls.py in the app looks like:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^patientlist', views.patient_list, name='patient_list'),
url(r'^patientdetail/(?P<pk>\d+)/$', views.patient_detail, name='patient_detail'),
url(r'^add_patient/$', views.add_patient, name='add_patient'),
]
The relevant part of views.py:
def add_patient(request):
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
form.save(commit=True)
return redirect('home')
else:
print form.errors
else:
form = PatientForm()
return render(request, 'spirit3/add_patient.html', {'form':form})
And the html looks like:
{% extends 'spirit3/base.html' %}
{% block content %}
<body>
<h1> Add a Patient </h>
<form action="/spirit3/add_patient/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Create Patient" />
</form>
</body>
{% endblock %}
Thanks in advance! :)
the form "action" attribute is wrong... seeing your urls configuration you dont have a /spirit3/add_patient/ url, I think It is /add_patient/
or you could just use a form tag without an "action" it will post to the current page:
<form role="form" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Create Patient" />
</form>
Hope this helps
As pleasedontbelong mentionned, there's indeed no url matching "/spirit3/add_patient/" in your current url config. What you have in tour root urlconf is:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include('spirit3.urls')),
]
This means that urls with path starting with "/admin/" are routed to admin.site.urls, and all other are routed to spirit3.urls. Note that this does NOT in any way prefixes urls defined in spirit3.urls with '/spirit3/', so in your case, all of these urls:
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^patientlist', views.patient_list, name='patient_list'),
url(r'^patientdetail/(?P<pk>\d+)/$', views.patient_detail, name='patient_detail'),
url(r'^add_patient/$', views.add_patient, name='add_patient'),
]
will be served directly under the root path "/" - ie, the add_patient view is served by "/add_patient/", not by "/spirit3/add_patient/".
If you want your spirit3 app's urls to be routed under "/spirit3/*", you have to specify this prefix in your root urlconf, ie:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^spirit3/', include('spirit3.urls')),
]
Note that you can use any prefix, it's totally unrelated to your app name.
As a last note: never hardcode urls anywhere, django knows how to reverse an url from it's name (and args / kwargs if any). In a template you do this with the {% url %} templatetag, in code you use django.core.urlresolvers.reverse().

how to send a parameter from html to django view.py

I am a beginner and did a lot of search but every time I got only "django to html" as search result every time. I am following this tutorial:
http://www.djangobook.com/en/2.0/chapter07.html
but on the way I am not able to pass paramter from html to view.py.
Here is my directory:
directory: mysite:
directory: books
directory: templates
search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
views.py
from django.shortcuts import render
from django.http import HttpResponse
def search_form(request):
return render(request, 'books/search_form.html')
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You submitted an empty form.'
return HttpResponse(message)
urls.py for books
from django.conf.urls import url,include
from . import views
urlpatterns = [
url(r'^$',views.search_form,name='search_form'),
url(r'^$', views.search,name='search'),
]
and urls.py in mysite directory
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Import the include() function: from django.conf.urls import url, include
3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^books/', include('books.urls')),
]
Now the problem is when I type: http://127.0.0.1:8000/books/
it successfully shows the form's textbox and submit button but when I press submit it shows me this:
Firstly, you need two different regexes for the search_form and search results. For example:
url(r'^$',views.search_form,name='search_form'),
url(r'^search/$', views.search,name='search'),
Next, you need to update the form's action to point to the search view. Since you have included your books/urls.py with the /books/ prefix, you need:
<form action="/books/search/" method="get">
It is better to use the url tag instead of hardcoding your urls. In this case, you would do:
<form action="{% url 'search' %}" method="get">
In addition to the answer of Alasdair I would use "books:search" for clear namespace:
<form action="{% url 'books:search' %}" method="get">
The url /search/ doesn't exist, you didnt define that it should exist.
It would be /books/ judging from that URLs file you showed. Also on a side note, don't use http://www.djangobook.com/en/2.0/index.html
They have a warning on the main page that it is no longer up to date.
Use masteringdjango.com and other up to date resources.

Django URLConf: page not found error

I am getting the error when resolving url http://127.0.0.1:8000/userprofile/auth. Below is my urls.py file for the userprofile app:
from django.conf.urls import patterns, url
from userprofile import views
urlpatterns = patterns('',
url(r'^$', views.login),
url(r'^auth/$' , views.auth_view),
url(r'^logout/$', views.logout),
url(r'/loggedin/$', views.loggedin),
url(r'/invalid/$', views.invalid_login),
)
The main urls.py is as follows:
from django.conf.urls import patterns, include, url
from userprofile import views
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^userprofile/', include('userprofile.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Here's a link to the screenshot of browser.
You should add the / slash to the action attribute of your <form>:
<form action="/userprofile/auth/" method="POST">
Or, as the better solution, name the url:
url(r'^auth/$' , views.auth_view, name='auth_view'),
and use the {% url %} tag in the template:
<form action="{% url 'auth_view' %}" method="POST">

Categories

Resources