NoReverseMatch - How to add url parameter to render? - django

Is there any method to provide url argument in case of render or any other solution? Somehow I need to provide user_url.
# view
def create_gallery(request, user_url):
if request.method == 'POST':
extended_form = GalleryExtendedForm(request.POST, prefix="extended_form")
basic_form = GalleryForm(request.POST, prefix="basic_form")
print(request.POST)
if extended_form.is_valid() and basic_form.is_valid():
pass
else:
extended_form = GalleryExtendedForm(prefix="extended_form")
basic_form = GalleryForm(prefix="basic_form")
return render(request, 'galleries/gallery_create_n_update.html',
{'extended_form': extended_form,
'basic_form': basic_form})
# core.urls
urlpatterns = [
url(r'^(?P<user_url>[\w.-]+)/', include('profiles.urls', namespace='profiles_user')),
]
# profiles.urls
urlpatterns = [
url(r'^gallery/', include('galleries.urls')),
# ... lots of others urls
]
# galleries.urls
urlpatterns = [
url(r'^add/$', views.create_gallery, name='gallery-add'),
]
Error:
django.urls.exceptions.NoReverseMatch: Reverse for 'gallery-add' with arguments '('',)'
and keyword arguments '{}' not found.
1 pattern(s) tried: ['(?P<user_url>[\\w.-]+)/gallery/add/$']

You should pass user_url into the context parameter of render(), so that it can be used in the template.
Then, inside the template, you can add user_url as a parameter to the url template tag, like this:
{% url 'gallery-add' user_url=user_url %}

Related

Django - pass the value for detail to template

There is a view for detail:
def get_viewNum(request, numNom):
md = Nomenclature.objects.get(pk=numNom)
all_changes_for_md = Changes.objects.filter(numNomenclature_id=md.numNom)
return render(request,'Sklad/viewNum.html',context = {'nomenclature':md, 'changes':all_changes_for_md})
There is also a view to display the table:
class TableView(ListView):
model = Nomenclature
context_object_name = 'nm'
template_name = 'Sklad/viewTable.html'
In template, I output a table and I want that when the button is clicked, there is a transition to the detail of the desired nomenclature.
My template:
///
{% for item in nm %}
<tr>
<td>{{item.numNom}}</td>
<td>{{item.nameNom}}</td>
<td>{{item.quantity}}</td>
<td>{{item.numPolk}}</td>
<td>Просмотр</td>
<td><button>Печать</button></td>
</tr>
{% endfor %}
///
How do I pass the desired numNom to the url detail string?
If you use this:
...
<td>Просмотр</td>
...
Returns an error:
NoReverseMatch at /table/ Reverse for 'prosmotr' with arguments
'('',)' not found. 1 pattern(s) tried: ['news/(?P[^/]+)/\Z']
My urls.py:
urlpatterns = [
path('', home, name='rashod'),
path('add_changes/',CreateChanges.as_view(), name = 'add_changes'),
path('save', save),
path('inventriz/', inventriz, name='invent'),
path('inventriz/inventr', inventr, name='add_invent'),
path('news/<str:numNom>/',get_viewNum, name='prosmotr'),
path('table/', TableView.as_view(), name = 'viewTable')
]
As your numNom is a CharField so the view should be:
def get_viewNum(request, numNom):
md = get_object_or_404(Nomenclature, numMom=numNom)
all_changes_for_md = get_list_or_404(Changes,numNomenclature=md)
#....
And in the html url:
...
<td>Просмотр</td>
...
``

django.urls.exceptions.NoReverseMatch: Reverse for 'Professors' with arguments '(1, 5)' not found

I'm trying to filter my professor table to display the professors that correspond to a specific school and specific major, the parameters are showing up in the error message, I just don't understand why there is a error message at all.
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, Major):
# major_choice = professor.objects.filter(Major =Major)
# return render(request, 'locate/major.html', {'major_choice': major_choice})
def Majors(request, school_pk):
schools_majors_ids = []
major_after_filter = []
#Filter to a show the association of 1 schools majors
school_choice = School_Major.objects.filter(school_id = school_pk)
#Append each of the major id's to school_majors_ids list
for store in school_choice:
schools_majors_ids.append(store.major_id)
#Filter majors names required
for store in schools_majors_ids:
name = Major.objects.get(id = store)
major_after_filter.append(name)
return render(request, 'locate/major.html', {'major_after_filter' : major_after_filter,
'school_pk' : school_pk})
def Professors(request, school_pk, major_pk):
professors = professors.objects.filter(school_id = school_pk).filter(major_id = major_pk)
return render(request, 'locate/professors', {'professors' : professors})
url.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path(' <int:school_pk>/', views.Majors, name='Major'),
path(' <int:school_pk/<int:major_pk>/', views.Professors, name="Professors")
]
majors.html
<h3 id="test">{{school_pk}}</h3>
<ul>
{% for major in major_after_filter %}
<li>{{major.name}}</li>
{%endfor%}
</ul>
I needed a way to place the value of the schools primary key, as well as the majors primary key as parameters for the Professor view function to be able to filter down the professor table in order to display the correct majors.
When I leave school_pk as seen below
I get the following error
django.urls.exceptions.NoReverseMatch: Reverse for 'Professors' with arguments '(1, 5)' not found. 1 pattern(s) tried: ['locate/\\ <int:school_pk/(?P<major_pk>[0-9]+)/$']
When I remove the school_pk like below
<li>{{major.name}}</li>
I get this error
TypeError: Professors() missing 1 required positional argument: 'school_pk'
Which makes sense because the professor function requires a school_pk parameter (Note that the variable used in the html and parameter are named the same sorry if that seems confusing).
You're missing a close bracket in your URL pattern.
path('<int:school_pk>/<int:major_pk>/',
^

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 [^/]+

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

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'),

NoReverseMatch at /

I am trying to make pretty meaningful urls, but I guess I'm doing it wrong.
This works:
from django.conf.urls.defaults import patterns, url
from places.views import explore_view
urlpatterns = patterns('',
url(r'', explore_view, name='explore'),
)
This does not:
from django.conf.urls.defaults import patterns, url
from places.views import explore_view
urlpatterns = patterns('',
url(r'(?P<countryorcategory>[0-9A-Za-z._%+-]+)', explore_view, name='explore'),
)
As I get this error:
Reverse for 'explore' with arguments '()' and keyword arguments '{}'
not found.
Here is the code for explore_view:
def explore_view(request, countryorcategory=None):
"""
This is the explore view - to view places sugeested by ambassadors
"""
user = request.user
page = request.GET.get("page", 1)
per_page = request.GET.get("per_page", 20)
category_id = request.GET.get("category_id", None)
attrs = request.GET
lat = safe_attr(attrs, "lat", "float", None)
lon = safe_attr(attrs, "lon", "float", None)
q = request.GET.get('q', None)
if q and not lat or lon:
cache_key = 'GoogleGeocode-{}'.format(hashlib.md5(q.encode('UTF-8', 'replace')).hexdigest())
latlon = cache.get(cache_key)
if not latlon:
latlon = geocode(q)
if latlon:
cache.set(cache_key, latlon)
if latlon:
lat = latlon['lat']
lon = latlon['lng']
if not q:
q = ''
category_names = getattr(settings, "EXPLORE_CATEGORIES", [])
categories = [Category.objects.get(name=cat_name).serialize() for cat_name in category_names]
more = True
places = Place.objects.explore_places(user, category_id=category_id, lat=lat, lon=lon, page=page, per_page=20)
if len(places) != per_page:
more = False
return render_to_response('explore/main.html', {'places': places, 'categories': categories, 'category_id': category_id, 'lat': lat, 'lon': lon, 'more': more, 'q': q}, RequestContext(request))
This line:
url(r'(?P<countryorcategory>[0-9A-Za-z._%+-]+)', explore_view, name='explore')
...is defining an url that takes an argument countryorcategory in the template. You need to put an argument on your url either of the following in your template:
{% url 'explore' argument %}
{% url 'explore' countryorcategory=argument %}
If you want to continue to use non-argument urls with the same name, you can define additional urls with the same name but with different patterns. For example:
urlpatterns = patterns('',
url(r'(?P<countryorcategory>[0-9A-Za-z._%+-]+)', explore_view, name='explore'),
url(r'', explore_view, name='explore'),
)
Then {% url 'explore' %} should work both with and without an argument.
For me, I forgot the namespace of the Route. Instead of
{% url 'login' %}
I should have written
{% url 'accounts:login' %}
with this configuration:
# root URLs
url(r'^accounts/', include('myproject.accounts.accounts.urls', namespace='accounts'))
# accounts URLs
url(r'^login$', views.login, name='login')
I'm assuming you are using a template with something like this :
{% url 'explore' argument %}
And this error probably means that the argument is not set to anything.