NoReverse Match at "" Reverse for "" with arguments '()' and keyword arguments '{}' - django

I'm trying to display a list of links to a list view in Django but I keep getting a "NoReverse Match" error.
Template
{% for posts in all_posts %}
{{posts.title}}
{% endfor %}
Views
from blog.models import Posts
from main_site.views import LayoutView
class BlogView(LayoutView, generic.ListView):
template_name = 'blog/blog.html'
model = Posts
context_object_name = 'all_posts'
Blog / urls
urlpatterns = patterns('',
url(r'^(?P<slug>\w+)/$', views.SingleView.as_view(), name='blog_single'),
url(r'^$', views.BlogView.as_view(), name='blog_home'),
)
Project /urls
urlpatterns = patterns('',
url(r'^blog/', include('blog.urls', namespace='blog')),
)
slug is property in my model set to models.SlugField() and if I output as just {{posts.slug}} it shows up so I know it's not empty. I have a similar link set up in a different app in the project that's working fine (exact same set up -- url 'namespace:name') so I'm not sure what's causing this to break.
The full error is:
NoReverseMatch at /blog/
Reverse for 'blog_single' with arguments '(u'test-slug',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'blog/(?P<slug>\\w+)/$']

this is because you have bad url pattern.
url(r'^(?P<slug>\w+)/$', views.SingleView.as_view(), name='blog_single'),
is expecting \w+ (that is any letter character, number character or underscore). But you are supplying it with a text containing a dash ("-").
So you need change your slug or url pattern to be like:
url(r'^(?P<slug>[\w-]+)/$', views.SingleView.as_view(), name='blog_single'),

Related

Reverse for 'update_cart' not found. 'update_cart' is not a valid view function or pattern name

I am new in django and i am developing one application in that on click i am trying to add product in cart. To select product i am using "{%url 'update_cart' product1.slug%}"> in my template, I am including my code here.
This is model
models.py
class cart(models.Model):
product=models.ManyToManyField(products,blank=True)
total=models.DecimalField(max_digits=100,decimal_places=2,default=0.00)
def __unicode__(self):
return "cart id: %s" %(self.id)
This is views
views.py
def cartpage(request):
c_data=cart.objects.all()[0]
return render(request,'cart/cart.html',{'c_data':c_data})
def update_cart(request,slug):
c_data = cart.objects.all()[0]
try:
product1=products.objects.get(slug=slug)
except products.DoesNotExist:
pass
except:
pass
if not product1 in c_data.product.all():
c_data.product.add(product1)
else:
c_data.product.remove(product1)
return HttpResponseRedirect(reverse("cart"))
This is urls
urls.py
path('cart/',views.cartpage,name='cart'),
path('cart/<slug:slug>',views.update_cart,name='update_cart')
I have created cart model and registered it in admin...its working properly even in my cart.html page is also working,but if i try to add product on click in cart page its giving me error.
please help
in urls.py of your app:
# imports
app_name = your_app_name
urlpatterns = [
# other urls
path('cart/',views.cartpage,name='cart'),
path('cart/<slug:slug>',views.update_cart,name='update_cart'),
]
in templates call urls by app namespace:
"{% url 'your_app_name:update_cart' product1.slug %}"
Refer here
Update:
make sure that product1.slug is there. If there is not, the url lookup will fail.
"Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/cart/(?P<slug>[-a-zA-Z0-9_]+)$'] "
means that, no arguments were passed to the url named update_cart. Here, the argument being product1.slug.
"{% url 'your_app_name:update_cart' product1.slug %}" seems you have passed. Check if slug is there for product1 object since product1.slug has not been rendered to the template.

Pulling data from db causing 404 page not found error

I'm trying to filter my views in such a way that when a specific school is chosen, pk of the school will be placed in a view function called major which would further query the db to display the proper majors corresponding to that school.
I now get a page not found 404 error, and can't figure out why.
url.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:Major>/', views.Major, name='Major')
]
models.py
from django.db import models
class Major(models.Model):
name = models.CharField(max_length=30, db_index=True)
class School(models.Model):
name = models.CharField(max_length=50, db_index=True)
school_Major_merge = models.ManyToManyField(Major, through='School_Major')
class School_Major(models.Model):
major = models.ForeignKey(Major, on_delete=models.CASCADE)
school = models.ForeignKey(School, on_delete=models.CASCADE)
class professor(models.Model):
ProfessorIDS = models.IntegerField()
ProfessorName = models.CharField(max_length=100)
ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4)
NumberofRatings = models.CharField(max_length=50)
#delete major from the model
school = models.ForeignKey(School , on_delete=models.CASCADE)
major = models.ForeignKey(Major , on_delete=models.CASCADE)
def __str__(self):
return self.ProfessorName
views.py
from django.http import HttpResponse
from django.shortcuts import render
from .models import professor, School, Major, School_Major
def index(request):
schools = School.objects.all()
return render(request, 'locate/index.html', {'schools': schools})
def Major(request, school_pk):
#Filter to a show the association of 1 schools majors
school_choice = Major_School.objects.filter(school_id = school_pk)
#Filter majors names required
majors = Major.objects.filter(id = school_choice.major_id)
return render(request, 'locate/major.html', {'majors' : majors})
I will post the code for the index file which pulls the schools info below, and when clicking on the school (hyperlink set) its basically suppose to pass the primary key of the school into the Major function which would then do further filtering.
<ul>
{% for list in schools %}
<li>{{list.name}}</li>
<br><br>
{%endfor%}
</ul>
The primary key for the school is pulled properly but for some reason the function doesn't fire up when I click on the hyperlink for the school I receive the 404 page not found error.
Purpose of the Major function,
1) Receive the Primary key of school, which will be passed to the M2M Table.
2) Now that ONLY majors corresponding to that school are displayed, Filter and store ONLY the majors which have the primary keys associated to the school chosen
I think the logic of my function is correct, I just can't understand again why i'm getting the 404 error.
Here is the exact error when I click the first school, which has a PK = 1
The current path, locate/{% url 'Major' 1/, didn't match any of these.
Update:
I went based on the suggestions below, and an example I had laying around that the format I have for the index.html is proper for the dispatcher, as well as the dispatcher is set properly aswell but WHY OH WHY does the {% still pop up I don't get it, I restarted the server thinking maybe it was bugging around but nada.
index.html
{% for list in schools %}
<li>{{list.name}}</li>
<br><br>
{%endfor%}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:school_pk>/', views.Major, name='Major')
]
The current path Error I'm having is still the same, but what I don't understand is after fixing the template to the proper format (I also used a example project I had as a reference that doesn't have this issue that passes a parameter) i'm not passing just the /locate/school_pk but the curly braces and the %
locate/ [name='index']
locate/ <int:school_pk>/ [name='Major'] <== This one
admin/
register/ [name='register']
profile/ [name='profile']
login/ [name='login']
logout/ [name='logout']
[name='blog-home']
about/ [name='blog-about']
post/<int:pk>/ [name='post-detail']
post/new/ [name='post-create']
post/<int:pk>/update/ [name='post-update']
post/<int:pk>/delete/ [name='post-delete']
user/<str:username> [name='user-posts']
^media/(?P<path>.*)$
The current path, locate/{% url 'Major' 1/, didn't match any of these.
Notice the {% is added in there, even after I fixed my mistake.
I think the template should be:
<li>{{list.name}}</li>
Where the URL is something like this:
path('<int:school_pk>/', views.Major, name='Major')
For reference please check the documentation.
In your for loop it should be
<ul>
{% for list in schools %}
<li>{{list.name}}</li>
<br><br>
{%endfor%}
</ul>
Just remove double curly braces {{ }}
So I noticed that there was a space between this specific url dispatcher in the error message
locate/ [name='index']
locate/ <int:school_pk>/ [name='Major'] <== This one
admin/
register/ [name='register']
profile/ [name='profile']
login/ [name='login']
logout/ [name='logout']
[name='blog-home']
about/ [name='blog-about']
post/<int:pk>/ [name='post-detail']
post/new/ [name='post-create']
post/<int:pk>/update/ [name='post-update']
post/<int:pk>/delete/ [name='post-delete']
user/<str:username> [name='user-posts']
^media/(?P<path>.*)$
The current path, locate/{% url 'Major' 1/, didn't match any of these.
So I added a space to the url.py which seemed to have done the trick
url.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path(' <int:school_pk>/', views.Major, name='Major')
]
All my other urls in my main project are setup the same way but don't have this problem, but for some reason everything i tried it wouldn't nudge, I had to place a space in order for it to work

Django how to use generic view with UUID instead of PK

I'm trying to access a url that's like
127.0.0.1:8000/posti/qNwEXBxXQdGI4KlQfoHWOA
However I can't resolve that smalluuid.
This is the error:
NoReverseMatch at /posti/ Reverse for 'detail' with arguments
'(SmallUUID('qNwEXBxXQdGI4KlQfoHWOA'),)' not found. 1 pattern(s)
tried: ['posti/(?P[0-9a-fA-F-]+)/$']
Django has issues trying to resolve it in another view that has a string like this:
from . import views
from django.conf.urls import url
app_name = 'posti'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<slug>[0-9a-fA-F-]+)/$', views.DetailView.as_view(), name='detail'),
My DetailView is this one:
class DetailView(generic.DetailView):
model = Post
template_name = 'posti/detail.html'
slug_field = 'uuid'
def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
return Post.objects.all()
I tried rewriting get_object but it didn't do anything. I don't understand if the regex is wrong or if my view has something wrong.
EDIT:
My template on index raised the error above and it had the following code:
{% if posti_list != null %}
<ul>
{% for post in posti_list %}
<li>{{ post.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>No posts are available.</p>
{% endif %}
I added slug_url_kwarg = 'uuid' to the DetailView class and now it works BUT now I have a
AttributeError at /posti/qNwEXBxXQdGI4KlQfoHWOA/ Generic detail view
DetailView must be called with either an object pk or a slug.
When I try to access the specific post.
I added slug_url_kwarg = 'uuid' to the DetailView class and now it works BUT now I have a
AttributeError at /posti/qNwEXBxXQdGI4KlQfoHWOA/ Generic detail view DetailView must be called with either an object pk or a slug.
slug_url_kwarg must match your url regex group name (slug in your case, which is default value for slug_url_kwarg), so you shouldn't have changed it
For details look at the piece of Django source code here - https://github.com/django/django/blob/master/django/views/generic/detail.py#L8

Error during template rendering

i am trying to render the details page of the product by giving the url www.example.com/product_name/product_id. But i am getting this error.
Reverse for 'product_details' with arguments '(u'lehnga choli', 43)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P[a-zA-Z]*)/(?P[0-9]+)/$']
here is my urls.py
url(r'^(?P<product_name>[a-zA-Z]*)/(?P<product_id>[0-9]+)/$', 'designer.views.product_details', name='product_details'),
and here is my urls in html template
{% url 'product_details' designs.name designs.id %}
and this is my views.py
def product_details(request, product_name, product_id):
design = Design.objects.get(id=product_id)
return render_to_response("designer/product_detail.html", {
"design":design,
"current": "product_detail",
}, context_instance=RequestContext(request))
There's a space in the name (which can't be used in a URL). As I mentioned in my comment, you might want to look into a SlugField
However, since you're looking up the Design by id in your view, it doesn't really matter whether the model has a slug. You can use the template tag slugify to just make it passable through the URL.
{% url 'product_details' designs.name|slugify designs.id %}
This does require a small tweak to your URL as well, because spaces are replaced with a - - and I just use \w in general.
url(r'^(?P<product_name>[\w-]+)/(?P<product_id>[0-9]+)/$', 'designer.views.product_details', name='product_details'),

Django issue - NoReverseMatch

I'm working on extending Horizon to include a custom app.
In that app, I have a DataTable:
class WorkloadsTable(tables.DataTable):
name = tables.Column("name", verbose_name=_("Name"))
description = tables.Column("description", verbose_name=_("Description"))
image = tables.Column("image", verbose_name=_("Image"))
flavor = tables.Column("flavor", verbose_name=_("Flavor"))
class Meta:
name = "workloads_table"
verbose_name = _("Workloads Table")
table_actions = (CreateNewWorkload, DeleteWorkload)
row_actions = (UpdateWorkload, DeleteWorkload)
which has a LinkAction:
class UpdateWorkload(tables.LinkAction):
name = "update"
verbose_name = _("Edit Workload")
url = "horizon:mydashboard:workloads_panel:update"
classes = ("ajax-modal",)
icon = "pencil"
def get_link_url(self, datum):
base_url = super(UpdateWorkload, self).get_link_url(datum)
workload_id = self.table.get_object_id(datum)
reversed = urlresolvers.reverse(self.url, args=[workload_id])
print reversed
return urlresolvers.reverse(self.url, args=[workload_id])
This LinkAction points to a routce in my urls.py:
WORKLOADS = r'(?P<workload_id>[^/]+)/%s$'
urlpatterns = patterns('',
url(r'^create/$', views.CreateView.as_view(), name='create'),
url(WORKLOADS % 'update', views.UpdateView.as_view(), name='update'),
url(r'^$', views.IndexView.as_view(), name='index'),
)
The issue is: When I enter the following url:
http://localhost:9000/mydashboard/workloads_panel/3/update
I get: NoReverseMatch: Reverse for 'update' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'mydashboard/workloads_panel/(?P<workload_id>[^/]+)/update$']
Where am I going wrong?
I guess the solution to your problem lies in the _update.html where you have to include the URL as,
{% block form_action %}
{% url 'horizon:mydashboard:workloads_panel:update' workload.id %}
{% endblock %}
while the workload.id is the object's id that you get in views.py in get_context_data function:
def get_context_data(self, **kwargs):
context = super(## the class name ##, self).get_context_data(**kwargs)
try:
context['workload'] = ##your API call ##(self.request,
self.kwargs['id'])
except Exception:
exceptions.handle(self.request)
return context
May be this will help you to resolve the error.
Well now the answer is quite simple. There is no matching URL for this reverse call:
{% url 'horizon:mydashboard:workloads_panel:update' %}
The update named URL pattern requires a valid workload_id argument matching your regex [^/]+