Reputation: 437
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?
Upvotes: 1
Views: 282
Reputation: 309099
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'),
Upvotes: 3