NoReverseMatch at / django 1.8 form - python

Im getting this error trying to load my index.html that has a form inside with a view call on the "action" tag.
NoReverseMatch at /
Reverse for 'create' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Request Method: GET
Request URL: http://localhost:8000/
Django Version: 1.8.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'create' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
This is my urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^create_project/$', views.create, name='create'),
]
This is my view.py:
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
def index(request):
return render(request, 'menu/index.html')
def create(request):
return render(request, 'menu/detail.html')
This is the index.html part that shows the action tag that raises the error:
<form class="nobottommargin" id="template-contactform" name="template-contactform" action="{% url 'create' %}" method="post">
{% csrf_token %}
<div class="col_half">
<label for="name">Project Name <small>*</small></label>
<input type="text" id="name" name="name" value="{{ current_name }}" class="sm-form-control required" />
</div>
I dont know what im doing wrong, hope you can help me!

I made a test with your data in the same Django version and work, check either because it must be something that is not there and has not imported.

The mistake was tha my urls have been included by another urls.py.
Thanks #Daniel Roseman

Related

Field 'id' expected a number but got <WSGIRequest: GET '/r/1/'>

i tried to make a project which would convert long url to short. take input url from html page and save it to database and redirect it to long url though my new url
but got an error
and the index.html looks like
<h1>short any url here</h1>
<form method="POST">
{% csrf_token %}
<input type="url" name="url" placeholder="enter your url here">
<input type="submit" value="submit">
</form>
{% for urlconverter in urlconv %}
<li>{{ urlconverter.short }} </li>
{% endfor %}
urls.py
from django.urls import path
from .import views
app_name='shorturl'
urlpatterns=[
path('shorturl/',views.indx,name='home'),
path('r/<int:urlconverter_id>/',views.redirect,name='redirect'),
]
the models.py
from django.db import models
# Create your models here.
class urlconverter(models.Model):
url=models.CharField(max_length=1000)
short=models.CharField(max_length=100)
def __str__(self):
return self.url
views.py
from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponse
from django.template import loader
from .models import urlconverter
# Create your views here.
def indx(request):
template=loader.get_template('urlconverter/index.html')
urlconv=urlconverter.objects.all()
if request.method=='POST':
a=request.POST.get('url')
b=urlconverter.objects.all()
c=b.count()
nwurl='/r/'+str(c)
s=urlconverter(url=a,short=nwurl)
s.save()
context={
'urlconv':urlconv
}
return HttpResponse(template.render(context,request))
def redirect(request,urlconverter_id):
obj=get_object_or_404(urlconverter,pk=urlconverter_id)
org_url=obj.url
return redirect(org_url,request)
and i got this error
TypeError at /r/1/
Field 'id' expected a number but got <WSGIRequest: GET '/r/1/'>.
Request Method: GET
Request URL: http://127.0.0.1:8000/r/1/
Django Version: 4.0.5
Exception Type: TypeError
Exception Value:
Field 'id' expected a number but got <WSGIRequest: GET '/r/1/'>.
could anyone please help me, where is the problem here?

Form Confirmation

I'm trying to pass data from a successful form submission to a thank you page that could then display this data. I am trying to do a reverse HttpResponseRedirect, but I keep getting this error:
NoReverseMatch at /contactform/process
Reverse for 'thankyou' with arguments '(24,)' not found. 1 pattern(s) tried: [u'contactform/thankyou/$']
Here is the code I have so far:
views.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
from .models import Contact_Object
def index(request):
template_name = 'contactform/index.html'
return render(request, 'contactform/index.html')
def thankyou(request, entered_id):
contact_info = get_object_or_404(Contact_Object, pk=contact_object_id)
template_name = 'contactform/thankyou.html'
return render(request, 'contactform/thankyou.html', {name: contact_info.name})
def process(request):
entered_name = request.POST['fullname']
entered_email = request.POST['email']
entered_message = request.POST['message']
entered = Contact_Object(name=entered_name, email=entered_email, message=entered_message)
entered.save()
entered_id = entered.id
return HttpResponseRedirect(reverse('contactform:thankyou', args=(entered.id,)))
urls.py
from django.conf.urls import url
from . import views
app_name = 'contactform'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^thankyou/$', views.thankyou, name='thankyou'),
url(r'^process$', views.process, name='process'),
]
Template for Form
<H1>Contact Form</H1>
<FORM action="{% url 'contactform:process' %}" method="post">
{% csrf_token %}
Full Name:<br>
<input type="text" name="fullname"><br>
Email:<br>
<input type="text" name="email" ><br>
Message:<br>
<textarea name="message" cols="40" rows="5"></textarea>
<input type="submit" value="Enter">
</FORM>
Template for Thank you page
<h1>Thank You</h1>
<p>Thank you, {% contact_info.name %}</p>
I'm new to working with Python/Django so I feel it's probably an obvious beginners mistake, I just can't seem to spot it.
Thanks in advance.
Your problem is right here:
return HttpResponseRedirect(reverse('contactform:thankyou', args=(entered.id,)))
the thankyou url doesn't take any arguments.
url(r'^thankyou/$', views.thankyou, name='thankyou'),
To fix it you should change it to this:
url(r'^thankyou/([0-9]*)$', views.thankyou, name='thankyou'),
Using the reverse function and the args kwarg, it translates it into a usable URL like: /thankyou/24 plugging in the args provided in the args iterable. You can also use kwargs to pass in keywords to your url if you're using keyword groupings in your url as described below.
See here: https://docs.djangoproject.com/en/1.11/topics/http/urls/#example
Each of the regex groupings is an argument that gets passed to the view.
You can also have keyword arguments passed if you do the url like this:
url(r'^thankyou/(?P<pk>[0-9]*)$', views.thankyou, name='thankyou'),
and in a function based view you would access it by defining it in the view function signature like this:
def thankyou(request, pk=None):

Django Error passing URL argument from Template to View: NoReverseMatch Reverse not found. 1 pattern(s) tried

I am trying to pass configure a URL like so:
/details/12345
Template HTML:
<div class="row">
{% if article_list %}
{% for article in article_list %}
<div>
<h2>{{ article.title }}</h2>
<p>{{ article.body }}</p>
<p><a class="btn btn-default" href="{% url 'details' article.id %}" role="button">View details ยป</a></p>
</div><!--/.col-xs-6.col-lg-4-->
{% endfor %}
{% endif %}
</div><!--/row-->
urls.py (full):
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'news_readr.views.home', name='home'),
url(r'^details/(?P<article_id>\d+)/$', 'news_readr.views.details', name='details'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py:
from django.shortcuts import render
from .models import Article
# Create your views here.
def home(request):
title = "Home"
article_list = Article.objects.all()
for article in article_list:
print(article.id)
context = {
"title": title,
"article_list": article_list,
}
return render(request, "home.html", context)
def details(request, article_id = "1"):
article = Article.objects.get(id=article_id)
return render(request, "details.html", {'article': article})
I am getting an error that says:
NoReverseMatch at /
Reverse for 'details' with arguments '()' and keyword arguments '{}'
not found. 1 pattern(s) tried: ['details/(?P<article_id>\\d+)/$']
I'm one week old at Django, and I think there's something wrong with my URL Named Group config. Please help! TIA!
Update: If I remove the URL config and change it back to:
url(r'^details/$', 'news_readr.views.details', name='details'),
The error changes to:
Reverse for 'details' with arguments '(1,)' and keyword arguments '{}'
not found. 1 pattern(s) tried: ['details/$']
So it seems to be picking up the argument that is passed 1 in this case. So this seems to be an issue with the regular expression. I tried the expression out at Pythex, but even there, the expression doesn't seem to be matching anything.
For the url pattern
url(r'^details/(?P<article_id>\d+)/$', 'news_readr.views.details', name='details'),
The correct way to use the tag is
{% url 'details' article.id %}
This because the details url pattern has a group article_id, so you have to pass this to the tag.
If you have the above url pattern, and {{ article.id}} displays correctly in the template, then the above template tag should not give the error Reverse for 'details' with arguments '()'. That suggests you have not updated the code, or you have not restarted the server after changing code.
If you change the url pattern to
url(r'^details/$', 'news_readr.views.details', name='details')
then you need to remove the article.id from the url tag.
{% url 'details' %}
I guess your pattern is wrong.( not an expert of regex ).
Try this
url(r'^details/((?P<article_id>[0-9]+)/$', 'news_readr.views.details', name='details'),

Django 1.7.4: Error on Django 1.7 tutorial04: NoReverseMatch error for Reverse for 'vote'

I have been banging my head against the wall all morning trying to complete the Django 1.7 tutorial04. I have read through all the similar posts on stackoverflow regarding the NoReverseMatch error, my error is slightly different:
Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found.
1 pattern(s) tried: [u'polls/(?P<question_id>\\d+)/vote/$'].
It appears it is choking on my details.html form action attribute:
<body bgcolor="white">
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question_id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
</body>
I have already defined the polls namespace in my main urls and got it working on my polls index page - the a tag inside the ul li is using {% url 'polls:detail' question.id %} and it works just fine.
My polls/urls.py looks like:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$',views.index, name='index'),
url(r'^(?P<question_id>\d+)/$', views.detail, name='detail'),
url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'),
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
)
Finally my polls/views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse,Http404
from django.http import HttpResponseRedirect, HttpResponse
from polls.models import Question,Choice
# Create your views here.
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question':question})
def results(request, question_id):
response = HttpResponse("You're looking at the results of question %s.")
return HttpResponse(response % question_id)
def vote(request, question_id):
p = get_object_or_404(Question, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# redisplay the question voting form
return render(request, 'polls/detail.html', {
'question': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
select_choice.save()
# always return response redirect after dealing with POST
# to prevent reposts if user hits back button
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
The error:
NoReverseMatch at /polls/1/
Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<question_id>\\d+)/vote/$']
Request Method: GET
Request URL: http://localhost:8000/polls/1/
Django Version: 1.7.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<question_id>\\d+)/vote/$']
Exception Location: /usr/local/lib/python2.7/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 468
Python Executable: /usr/bin/python
Python Version: 2.7.9
Any assistance would be greatly appreciated. Thank you for reading.
Instead of question_id, try using question.id in the template, i.e.:
<form action="{% url 'polls:vote' question.id %}" method="post">

Is there a type discrepancy that is causing this 'NoReverseMatch' in Django?

According to the Django docs, a NoReverseMatch happens when "a matching URL in your URLconf cannot be identified based on the parameters supplied."
I am getting the following NoReverseMatch error. My question is: why is the parameter supplied not being caught by the url? Is it expecting a parameter of a different type? I'm still not too comfortable with Django urls.
"Reverse for 'recall' with arguments '(<Unordered_Group: countries>,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []"
This question is revised from Django NoReverseMatch url issue after suggestions were tried.
edited:
images/urls.py (project level)
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^images/', include('images_app.urls', namespace="images_app")),
url(r'^associate/', include('associate.urls', namespace="associate")),
url(r'^admin/', include(admin.site.urls)),
)
associate/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^learn/', "associate.views.learn", name='learn'),
url(r'^recall/(?P<ordered_group>\w+)', 'associate.views.recall', name='recall'),
url(r'^$', "associate.views.index", name='index'),
)
learn.html
<form action="{% url 'associate:recall' ordered_group %}" method="post"> ERROR CAUGHT
{% csrf_token %}
<div>
<label for="recall">enter as many members of {{ ordered_group }} as you can recall </label>
<input type="text" id="recall" name="recall">
</div>
<div id="enter_button">
<input type="submit" value="enter" name="enter" />
</div>
<div id="done_button">
<input type="submit" value="done" name="done" />
</div>
</form>
views.py
def recall(request, ordered_group):
...
def learn(request):
...
ordered_group = ordered_groups[index]
return render(request, 'associate/learn.html', {'dataset':model, 'ordered_group':ordered_group})
The issue is, your URL pattern is expecting a regex which matches [\w]+ which is one or more wordcharacters.
recall/(?P<ordered_group>\w+)
But it actually got an object.
A better way of doing this would be to send the id of the ordered group object (or any other unique identifier), and querying for that object in the view again.
Note that if you go with the id, URL pattern regex would be
recall/(?P<ordered_group>\d+)
and the view:
def recall(request, ordered_group):
obj = get_object_or_404(Unordered_Group, id=ordered_group)
#rest of the code..

Categories