1

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?

1 Answer 1

3

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'),
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, but when I tried that, it gives me "'EquipmentForm' object has no attribute 'id'"
I didn't spot that post was a form, not a Post. That's very confusing! Use form for your form, and post for your Post instance, it will make your code easier to understand! I've updated the answer now.
Sorry for the confusion. And thanks so much for helping. I tried your updates and it is now "Reverse for 'default_detail' with arguments '(28,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['calbase/default/((?P<id>\\d+)/$)']". I am wondering if the problem is with the urls?
Maybe you have not set up the calbase namespace. Try reverse('default_detail', args=(post.id,))
I am pretty sure that I set up the namespace fine and yeah i also tried doing that and still. This is driving me crazy...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.