An NoReverseMatch Error - python

I know that NoReverseMatch problem means something wrong with my URLs, but I just could not find where the problem is
views.py:
def edit(request,post_id):
e = Note.objects.get(id=post_id)
form = Edit()
if request.method == 'POST':
form = Edit(request.POST.copy())
if form.is_valid():
data1 = form.cleaned_data
g = Note.objects.get(id=post_id)
g.title = data1['title']
g.content = data1['content']
g.category = data1['category']
g.subject_name = data1['subject_name']
g.save()
return HttpResponseRedirect('/notebook/')
else:
return HttpResponse('Not good')
else:
form = Edit(initial={'title': e.title,'content': e.content, 'category' : e.category,
'subject_name': e.subject_name})
return render(request,'notebook/edit.html',{'form': form})
in urls.py:
urlpatterns = [
url(r'^$', views.homepage, name='homepage'),
url(r'^(?P<post_id>[0-9]+)/$', views.detail, name='detail'),
url(r'^(?P<post_id>[0-9]+)/delete/$', views.delete, name='delete'),
url(r'^edit/(?P<post_id>[0-9]+)/$', views.edit, name='edit'),
url(r'^/post/$', views.post, name='post'),
url(r'^category(?P<category>\w+)/$', views.show_category, name='show_category'),
url(r'^subject(?P<id>\w+)/$', views.show_subject, name='show_subject'),
url(r'^/create_subject/$', views.create_subject, name='create_subject'),
# url(r'/upload_image/$', views.upload_image, name='upload_image'),
]
The Error:
Reverse for 'edit' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['notebook/edit/(?P<post_id>[0-9]+)/$']
And by the way, I have to say this, which I think is important, before I added the class Subject, which means the form had nothing to do with it in the first place, the function edit() worked just fine.
And besides, parts of my form looks like this:
class Edit(forms.Form):
title = forms.CharField(label=('title')
content = forms.CharField(label=('content'),widget=forms.Textarea)
category = forms.CharField(label=('category')
subject_name = forms.ModelChoiceField(queryset=Subject.objects.all())

You are most likely using a url filter tag in your template. You need to pass the post_id as a parameter in your url filter tag.
{% url 'edit' post_id %}
On a side note, you should preferably use reverse or reverse_lazy to get url's rather than hard coding them
from django.core.urlresolvers import reverse_lazy, reverse
HttpResponseRedirect(reverse('url_name'))

Related

is it possible to attach a string variable in return redirect() in django

I have a situation here where I am creating a record from a view
def index(request):
if request.method == "POST":
order_number = request.POST.get('order_number')
post_code = request.POST.get('post_code')
print(order_number)
print(post_code)
if order_number and post_code:
n = page1.objects.create(orderNumber=order_number, postCode=post_code)
n.save()
id = n.id
return redirect("page1:waiting")
return render(request,"page1/index.html")
And upon creating the record I am redirecting the user to another page with id.
127.0.0.1/page1/waiting/fb65-io98-.....
from django.urls import path
from . import views
app_name = 'page1'
urlpatterns = [
path('', views.index, name="amounts"),
path('waiting/<str:pk>', views.waitReply, name="waiting"),
]
View for Second URL
def waitReply(request,pk):
get_amount = page1.objects.get(id=pk)
context = {'get_amount':get_amount}
return render(request, "page1/payment-confirm.html", context)
But the problem is how do I attach/generate/get the id in index view and send it for the waitReply view
I can get the latest ID through n.id
Kindly help.
Use reverse with args in HttpResponseRender.
return HttpResponseRender(reverse('page1:waiting' args=[id]))

Django-2.2 NoReverseMatch error. Cannot redirect to next page

After submission of a create form in my web app it should redirect in to a single page where it displays the new product that is entered. instead of that, it shows :
Reverse for 'category' with keyword arguments '{'pk': UUID('e3ec4273-22c9-450f-87c9-d12973dce3c1')}' not found. 1 pattern(s) tried: ['app/products/category/<int:pk>']
views.py
def create_category(request):
if request.method=='POST':
form = CategoryForm(request.POST,request.FILES)
if form.is_valid():
data = form.save(commit=False)
data.creator = request.user
data.updater = request.user
data.auto_id = get_auto_id(ProductCategory)
data.save()
return HttpResponseRedirect(reverse('products:category',kwargs={"pk":data.pk}))
else:
...
else:
...
def category(request,pk):
instance = get_object_or_404(ProductCategory.objects.filter(pk=pk))
context = {
'title': "Category : " + instance.name,
'instance' : instance,
}
return render(request,'products/category.html',context)
urls.py
from django.urls import path
from . import views
app_name = 'products'
urlpatterns = [
path('categories',views.categories,name='categories'),
path('category/create',views.create_category,name='create_category'),
path('category/<int:pk>',views.category,name='category'),
path('category/edit/<int:pk>',views.edit_category,name='edit_category'),
path('category/delete/<int:pk>',views.delete_category,name='delete_category'),
]
Th thing is the form is submitted and the values are added to database. But it doesn't move to the next step.
I am new to django 2 so not very sure on how to pass pk in urls/path
In your url:
path('category/<int:pk>',views.category,name='category'),
^^^^
You are expecting an integer but in code you are passing an UUID. So change the url to:
path('category/<uuid:pk>',views.category,name='category'),
More information can be found in documentation.

Django - TypeError at feeds() missing 1 required positional argument: 'id'

I'm trying to add comments to my project and I've got this error: feeds() missing 1 required positional argument: 'id'. Here is my code.
views.py
#login_required
def feeds(request, id):
feeds_list = Feed.objects.all()
feed = get_object_or_404(Feed, id=id)
users = User.objects.filter(is_active=True)
if request.method == 'POST':
# Komentarz zostaƂ opublikowany.
feed_form = FeedForm(request.POST)
if feed_form.is_valid():
# Utworzenie obiektu Comment, ale jeszcze nie zapisujemy go w bazie danych.
new_feed = feed_form.save(commit=False)
new_feed.user = request.user
new_feed.date = timezone.now
# Zapisanie komentarza w bazie danych.
new_feed.save()
else:
feed_form = FeedForm()
context = {'section': feeds,
'users': users,
'feeds_list': feeds_list,
'feed_form': feed_form}
return render(request, 'feed/list.html', context)
I think that's here is problem: feed = get_object_or_404(Feed, id=id), but I don't know how to solve it.
Thanks for help.
Edit:
urls.py
from django.contrib.auth.urls import url
from . import views
app_name = 'feedApp'
urlpatterns = [
url(r'^$', views.feeds, name='feeds'),
url(r'^feed/new$', views.post_new, name='post_new'),
url(r'^feed/(?P<id>[0-9]+)/$', views.feed, name='post_detail'),
# url(r'^feed/(?P<id>[0-9]+)/comment$',
# views.comment_feed,
# name='comment_feed'),
url(r'^feed/(?P<id>[0-9]+)/delete/$',
views.feed_delete,
name='feed_delete'),
]
as per your urls you need to add the required argument id to it.
edit your url to :
url(r'^(?P<id>[0-9]+)$', views.feeds, name='feeds'),
You have not used 'id' as keyword args in views.feeds url.
Add url(r'^feed/(?P<id>[0-9]+)/$', views.feeds,),

django - python: failed using reverse : no reverse match

I have the following Views:
def default_new (request):
if request.method == "POST":
post = EquipmentForm(request.POST)
if form.is_valid():
post.save()
return HttpResponseRedirect(reverse('calbase:default_detail', args=(id,)))
else:
form = EquipmentForm()
return render(request, 'calbase/default_edit.html', {'form':form})
class default_detail (generic.DetailView):
model = Equipment
template_name = 'calbase/default_detail.html'
And urls:
urlpatterns = [
url(r'^$', views.default, name = 'default'),
url(r'^default/((?P<id>\d+)/$)', views.default_detail.as_view(), name = 'default_detail'),
url(r'^default/new/$', views.default_new, name = 'default_new'),
]
What I would like to do here is just to take in a form input, save it, and then redirect to its detail view. However, although the form is correctly saved, it always give me errors like:
NoReverseMatch at /calbase/default/new/
Reverse for 'default_detail' with arguments '(<built-in function id>,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['calbase/default/((?P<id>\\d+)/$)']
Could somebody help me figuring out what's wrong here pls?
The problem is you are using id, which is a built in function.
When you call form.save(), it will return the Post instance. Use post.id (or post.pk if you prefer) to get the id of the post.
def default_new(request):
if request.method == "POST":
form = EquipmentForm(request.POST)
if form.is_valid():
post = form.save()
return HttpResponseRedirect(reverse('calbase:default_detail', args=(post.id,)))
You also have too many parentheses in your url pattern. It should be:
url(r'^default/(?P<id>\d+)/$', views.default_detail.as_view(), name = 'default_detail'),

How to solve NoReverseMatch in django1.8.6

Recently I wrote an app called notebook, and I came across this NoReverseMatch issue.Really hope someone could help me out.
Here are my codes.
in views.py:
def note_add(request):
if request.method == 'POST':
form = NoteForm()
category = CategoryForm()
if form.is_valid() and category.is_valid():
data1 = form.cleaned_data
data2 = category.cleaned_data
category_name = data2['category_name']
for category_list in category_name.split():
Category.objects.get_or_create(category_name=category_list.strip())
title = data1['title']
content = data1['content']
note = Note(title=title, content=content)
note.save()
id = Note.objects.order_by('-id')[0].id
return HttpResponseRedirect('/notebook/note_add/%s' % id)
else:
form = NoteForm()
category = CategoryForm()
return render_to_response('notebook/note_add.html',{'form':form, 'category':category})
in notebook/urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.note_list, name='note_list'),
url(r'^/note_add/$,', views.note_add, name='note_add'),
url(r'^(?P<id>[0-9]+)/$', views.note_detail, name='note_detail'),
url(r'^edit/(?P<id>[0-9]+)/$', views.edit, name='edit'),
url(r'^category/(?P<id>[0-9]+)/$', views.note_category, name='note_category'),
]
The problem description is
NoReverseMatch at /notebook/
Reverse for 'note_add' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['notebook//note_add/$,']
Remove the first "/" in urls.
url(r'^note_add/$,', views.note_add, name='note_add'),
Like that.
From what i have seen "no reverse match" was usually because of errors in urls

Categories

Resources