I am attempting to create a simple forum application and am getting this error. I am inclined to think this may have something to do with my URLConf or possibly the way I am using the URL template tag to generate the URL for each thread.
/forums/urls.py
# ex: /forums/general_forum
url(r'^(?P<forum_slug>[-\w\d]+)/$', views.forum, name='forum'),
# ex: /forums/general_forum-1/my_first_thread
url(r'^(?P<forum_slug>[-\w\d]+)/(?P<thread_slug>[-\w\d]+)/$', views.thread, name='thread'),
/forums/views.py
The index view works fine, the forum view does not.
def index(request):
context = RequestContext(request)
forum_list = Forum.objects.order_by("sequence")
for forum in forum_list:
forum.url = slugify(forum.title) + "-" + str(forum.id)
context_dict = {'forum_list': forum_list}
return render_to_response('forums/index.html', context_dict, context)
#login_required
def forum(request, forum_slug):
context = RequestContext(request)
try:
forum = Forum.objects.get(slug=forum_slug)
threads = Thread.objects.filter(forum=forum)
context_dict = {'forum': forum,
'threads': threads}
except Forum.DoesNotExist:
pass
return render_to_response('forums/forum.html', context_dict, context)
This is how I am linking to the forum view inside index.html.
<a href={% url 'forum' forum.slug %}>{{ forum.title }}</a>
And in forum.html, this is how the links are formulated to view the posts inside the thread. This :
<a href={% url 'forum' forum.slug %}/{% url 'thread' thread.slug %}>{{ thread.title }}</a>
The error. One of the threads is titled 'django'
NoReverseMatch at /forums/web-development/
Reverse for 'thread' with arguments '(u'django',)' and keyword arguments '{}' not found. 2 pattern(s) tried: ['forums/(?P<forum_slug>[-\\w\\d]+)/(?P<thread_slug>[-\\w\\d]+)/$', '$(?P<forum_slug>[-\\w\\d]+)/(?P<thread_slug>[-\\w\\d]+)/$']
In the error, the url template tag for 'thread' is highlighted in red and states there was an error during template rendering. This error seems unclear to me and I am not sure if this is an issue with the way I am using the template tags or something else.
You're not passing the Forum slug in your thread URL, which your URL configuration requires:
<a href={% url 'forum' forum.slug %}/{% url 'thread' thread.slug %}>{{ thread.title }}</a>
You should not be using both urls, either. Instead, what you want is:
{{ thread.title }}
Related
In my online store django project, I want to create a sub-page which shows the details of a product that is listed in a page.
in urls.py I created the urls for both pages like bellow:
path('wwqm', views.water_quality_sensor , name='wwqm'),
path('wwqm/<str:water_sensor_title>', views.water_sensor_item, name='water_sensor_item'),
in this scenario, a bunch of items are being shown in wwqm. user click on a product and the water_sensor_item should load up.
I know its not important but here is views.py:
def water_quality_sensor(request):
queryset_list = Water_quality_sensor.objects.order_by('-product_name').filter(is_published=True)
context = {
'water_quality_sensor': queryset_list,
}
return render(request, 'products/water_quality_sensor.html', context)
def water_sensor_item(request, water_sensor_title):
water_sensors = get_object_or_404(Water_quality_sensor, title=water_sensor_title)
context = {
'water_sensors': water_sensors
}
return render(request, 'products/water_sensor_item.html' , context)
I try to build the url for each item based on a parameter that is passed to its view(products title).
In my templates, I try to create a link like the following:
<a href="{% url 'water_sensor_item' w_q_sensor.title %}" class="card hoverable mb-4 text-dark" >
one my products' title is 3725. when I click on that product in the main page, I get the following error:
Django Version: 3.1.2
Exception Type: NoReverseMatch
Exception Value: Reverse for 'water_quality_sensor' not found. 'water_quality_sensor' is not a valid view function or pattern name.
What am I doing wrong?
in your urls.py
path('wwqm', views.water_quality_sensor , name='wwqm'),
you used name wwqm. But it looks like somewhere in your template (most likely water_sensor_item.html), you have something similar to :
<a href="{% url 'water_quality_sensor' %}"
Change it to wwqm or change name in urls.py
UPDATE
It is better to use <str:title><int:pk> in your urls, to avoid when you have the same name in two products. pk is unique.
in your urls.py
path('wwqm/<str:water_sensor_title><int:pk>', views.water_sensor_item, name='water_sensor_item'), # add <int:pk>
in your template:
# since url is taking both title and pk arguments, you need to provide both of them.
<a href="{% url 'water_sensor_item' title= w_q_sensor.title pk=w_q_sensor.pk %}" class="card hoverable mb-4 text-dark" >
in your view:
def water_sensor_item(request, water_sensor_title, pk): # added pk
water_sensors = get_object_or_404(Water_quality_sensor, pk=pk) # use pk to get the object
context = {
'water_sensors': water_sensors
}
return render(request, 'products/water_sensor_item.html' , context)
I want a URL something like this:
/(category)/(post-slug)
On the link this is what I have:
{% url blog.category blog.slug %}
and for the url.py:
url(r'^(I DON"T KNOW WHAT TO PUT ON THIS PART TO GET THE CATEGORY)/(?P<slug>[0-9A-Za-z._%+-]+)', views.post, name='post'),
thanks
EDIT:
This is what I have now:
Still have NoReverseMatch error at /
urls.py
url(r'^(?P<category>[0-9A-Za-z._%+-]+)/(?P<slug>[0-9A-Za-z._%+-]+)$', views.post, name='post'),
index.html
<a href="{% url blog.category blog.slug %}">
views.py
def post(request, slug, category):
try:
blog = Blog.objects.get(slug=slug)
except Blog.DoesNotExist:
raise Http404('This post does not exist')
return render(request, 'parts/post.html', {
'blog': blog,
})
Firstly, your URL tag needs the name of the pattern you are reversing as the first argument:
{% url 'post' blog.category blog.slug %}
or if you are using a namespace, something like:
{% url 'blog:post' blog.category blog.slug %}
You haven't shown your views or models, so we can only guess what your URL pattern should be. I'm not sure why you find the category confusing - you just need to choose a name for the group (e.g. category_slug), and the regex for the group (you might be able to use the same one as you use for slug). That would give you:
url(r'^(?P<category_slug>[0-9A-Za-z._%+-]+)/(?P<slug>[0-9A-Za-z._%+-]+)$'
Note that there should be a dollar on the end of the regex.
I've been trying to figure this out for a while now but I feel like I don't know the framework well enough to debug this myself.
Basically I'm creating a little blog style site and I'm trying to create a list of posts which can link to the page to read the post itself.
I have a for loop in my template:
templates/home.py
<h1>Home Page</h1>
<p>welcome to the ven home page, {{ username }}!</p>
Click here to log out
<br>
Click here to create a post
<h2>Posts:</h2>
{% for post in posts %}
<div>
<hr>
<h4>{{post.title}}</h4>
<p>{{post.body}}</p>
<p><i>{{post.tags}}</i></p>
</div>
{% endfor%}
It's the line <h4>{{post.title}}</h4> which is causing the problem. I'm getting the error
Reverse for 'show' with keyword arguments '{'id': 1}' not found. 1
pattern(s) tried: ['posts/(?P<post_id>\\d+)/view/$']
here is my urls file
url(r'^$', views.CreateFormView.as_view(), name='create'),
url(r'^(?P<post_id>\d+)/view/$', views.show_post, name='show')
The create method link works fine
and here is the view which loads the template:
def home(request):
if not request.user.is_authenticated:
return redirect('users:login')
posts = Post.objects.all()
username = request.user.username
return render(request, 'ven/home.html', {'username': username, 'posts':
posts})
If more information is needed then let me know and I will provide it.
All other answers have said that this error is to do with the namespace, but it's working fine with the create link so I'm stumped.
Thanks in advance!
The argument names are mismatching.
You'd want to change <h4>{{post.title}}</h4>
to
<h4>{{post.title}}</h4>
Since in urls.py the show url is defined as '^(?P<post_id>\d+)/view/$'.
I am trying to pass parameter from url. I have tried many tutorials and can't figure out what am i doing wrong.
my url from url.py:
url(r'^reports/(?P<test>\d+)/$', views.reports,name='reports'), # report view
my view from view.py:
def reports(request, test=0 ):
title = "Reports" # title shown in browser window
view ="admin/pc/reports.html"# where is the page view
user_name = request.user.get_username() #User name
return render(request, 'admin/home.html', {"title":title,"USER_NAME" : user_name,"page" : view, 'pid':test})
and my template:
{% block content %}
REPORTSz id = {{pid }}
{% endblock %}
but no matter what I do I always get:
Reverse for 'reports' with arguments '()' and keyword arguments '{}'
not found. 1 pattern(s) tried: ['admin/reports/(?P\d+)/$']
So my question is how to correctly pass parameter from url?
In url tag in Django templates, you need to pass your test parameter:
href="{% url "reports" test="some_value" %}"
because test parameter is required in your URL.
I'm trying to make a simple search and return results in a paginated form. Whenever I try to go to the second page, my search term is lost and thus my second page has no results.
I've found and followed the Pagination example in the Djangoproject tutorial, but I haven't found an example on how to write my URL for the search view.
I've used POST method in my form previously, for when I had little data to display (although now, after a bit of research, I know the usage difference between GET and POST). When I gained lots more data, I was constrained to use Pagination. Thus, I've changed my form method to GET but here is my problem, I don't know how to describe my URL so the data is sent to the right view.
I've tried to make it work with POST but with no success. Finally I decided to stick to GET example but stumbled on this URL thing that's keeping me back.
Here is the code in the template and the URLs file:
search.py:
<form method="GET" id="searchForm" action="/search/?page=1">
{% csrf_token %}
<input type="text" id="billSearched" name="q_word">
<input type="submit" value="{% trans "Look for" %}">
</form>
urls.py:
urlpatterns = patterns('',
url(r'^$','ps.views.bills',name="bills"),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^search/$','ps.views.search',name="search"),)
I've tried many forms for the URL but none have succeeded.
i.e.:
url(r'^search/(?P<page>\d+)/$','ps.views.search',name="search")
url(r'^search/','ps.views.search',name="search")
url(r'^search/(?P<page>\d+)/(?P<searchTerm>\w*)','ps.views.search',name="search")
Any explanation / solution would be really appreciated. Thank you in advance!
UPDATE:
def search(request):
searchTerm = ""
page = 1
import pdb
pdb.set_trace()
if 'q_word' in request:
searchTerm = request.GET['q_word']
if 'page' in request:
page = request.GET['page']
found_bills = Bill.objects.filter(name__icontains = searchTerm)
paginator = Paginator(found_bills,25)
try:
current_page = paginator.page(page)
except PageNotAnInteger:
current_page = paginator.page(1)
except (EmptyPage, InvalidPage):
current_page = paginator.page(paginator.num_pages)
bills_list = list(current_page.object_list)
return render_to_response('results.html',{"bills_list":bills_list,"current_page":current_page,},context_instance=RequestContext(request))
UPDATE #2:
If I use pdb I can see that there is no data being passed from the client to the server. Got to work on that, but still, any information and/or hints would be really appreciated as they can shorten my search time :)
(Pdb) request.GET
<QueryDict: {u'page': [u'1']}>
If your form's method is GET, you cannot append a query string to the action, because the browser will overwrite it. You can only do that if your form method is POST.
Change your form to this:
<form method="GET" id="searchForm" action="/search/">
<input type="text" id="billSearched" name="q_word">
<input type="submit" value="{% trans "Look for" %}">
</form>
In your view:
from django.shortcuts import render
def search(request):
if 'q_word' in request:
searchTerm = request.GET['q_word']
found_bills = Bill.objects.filter(name__icontains = searchTerm)
page = request.GET.get('page')
paginator = Paginator(found_bills,25)
try:
current_page = paginator.page(page)
except PageNotAnInteger:
current_page = paginator.page(1)
except (EmptyPage, InvalidPage):
current_page = paginator.page(paginator.num_pages)
# bills_list = list(current_page.object_list) - not needed
return render(request,
'results.html',{"results":current_page,"term": searchTerm})
In results.html:
{% for bill in results %}
# .. display bill stuff
{% endfor %}
{% if results.has_previous %}
previous
{% endif %}
{% if results.has_next %}
next
{% endif %}
What do you mean by 'describe' your url? Your urls.py look fine. Did you drop a debugger into your ps.views.search() function to verify that it is hitting? Did you look at your debug server logs to make sure the right url is being requested from the browser?
you can either have r'^search/$' and access the page param as request.GET['page'] or you can pass in the param to your view function like url(r'^search/(?P<page>\d+)/$ which would mean search would take 2 params request and then page. If passing in the page param you need to change your form URL to be
<form method="GET" id="searchForm" action="/search/1">
Instead of having page be a GET param
I don't see anything wrong with your syntax for any of the urls you've listed.
https://docs.djangoproject.com/en/1.3/topics/pagination/#using-paginator-in-a-view
If you are using url(r'^search/(?P<page>\d+)/$' make sure that search takes a variable named page as a second argument. It is important to learn how to use the debugger too.
import pdb; pdb.set_trace() (or even better ipdb!), Drop that in your view to see if its hitting, If its not hitting check dev server to see what url is actually being requested.