0

This subject is continuation of thinking in this topic. I fell back in problem of reverse in generic views. Last time I thought it's no reverse match because I used many to many, now I haven't many to *** relations in reverse but problem still in there. Since I have generic view in urls in both cases, I suggested the problem is in generic views and no view function. At first I used @permalink decorator in the models

...
@permalink
def get_absolute_url(self):
    return ('categories', str(self.id))
...
@permalink
def get_absolute_url(self):
    return ('pages', (), {'page_name': self.human_readable_url})

urls

url(r'^(?P<page_name>&\w*)?/?$', direct_to_template,
    {'template': 'basic.djhtml'},
    name = "pages"),
url(r'cat/\d+/$',
    direct_to_template,
    {'template': 'basic.djhtml'},
    name = "categories")

And got an error:

NoReverseMatch: Reverse for 'pages' with arguments '()' and keyword arguments '{'page_name': u'page1'}' not found.

Then I tried reverse method

def get_absolute_url(self):
    return reverse('categories', args = [self.id, ])

And have the same error

NoReverseMatch: Reverse for 'categories' with arguments '(2,)' and keyword arguments '{}' not found.

Based on the fact that permalink not explicitly use reverse method, I think that the problem is in interaction reverse and generic view in url. Why is it happens? How to use reverse in url generic views?

1 Answer 1

1

The problem is, you have given the name categories to a generic view, direct_to_template, and you are passing an argument to that view - but direct_to_template doesn't take that argument, only a dictionary containing extra context.

If you want to pass additional arguments to a generic view, you can - but they will only be passed on to the Template. You can extend the view by writing your own function, which adds the parameter into a dictionary, then calls the generic view. Something like this:

# views.py
from django.views.generic.simple import direct_to_template

def my_view(id):
    more_data = {'id': id}
    return direct_to_template(template = 'basic.djhtml', more_data)

And then in your urls.py, replace the direct_to_template with my_view. Since my_view takes an id argument, reverse will properly match it, and the argument will be passed in to the generic view, and through to the template.

Presumably somewhere in your template is a line such as, {{ id }}.

Sign up to request clarification or add additional context in comments.

Comments

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.