Вопрос

Finally upgraded a project to 1.6 and now I'm having trouble with URLs and Class Based Views.

I have a form that starts like this:

<form action="{{ project.get_absolute_url }}" method="post" id="editproject" >

And the project model includes this:

@permalink
def get_absolute_url(self):
    return  ('project_url', (), {'slug': self.slug})

On trying to load the page I'll get this error:

NoReverseMatch at /teamslug1/projectslug1/teamid1/projectid1/
Reverse for 'project_url' with arguments '()' and keyword arguments '{'slug': u'projectslug1'}' not found. 1 pattern(s) tried: ['(?P<teamslug>[^\\.]+)/(?P<projectslug>[^\\.]+)/(?P<teamid>[^\\.]+)/(?P<projectid>[^\\.]+)/$']

If I wrap the form variable in quotes:

<form action="{{ "project.get_absolute_url" }}" method="post" id="editproject" >

It won't error out on loading but when I POST with the form it'll result in an url like this: http://0.0.0.0:5000/teamslug1/projectslug1/teamid1/projectid1/project.get_absolute_url, which doesn't exist.

Here's the urls.py info:

url(r'^(?P<teamslug>[^\.]+)/(?P<projectslug>[^\.]+)/(?P<teamid>[^\.]+)/(?P<projectid>[^\.]+)/$', 'ideas.views.projects', name='project_url'),

Any ideas?

Это было полезно?

Решение

This doesn't look like a problem specific to Django 1.6 or class based views. The problem is that the get_absolute_url method doesn't match the URL pattern.

Firstly, wrapping the variable in quotes is definitely incorrect. Django treats it as a string, your browser treats it as a relative link, and posts the form to the wrong URL.

The project_url URL pattern has four keyword arguments but your get_absolute_url method only specifies slug, which isn't one of those arguments. I would expect your get_absolute_url method to look something like:

@permalink
def get_absolute_url(self):
    return  ('project_url', (), {'teamslug': self.teamslug,
                                 'projectslug': self.projectslug,
                                 'projectid': self.projectid,
                                 'teamid ': self.teamid,
    })

Note that the docs recommend that you use reverse instead of the permalink decorator.

from django.core.urlresolvers import reverse

def get_absolute_url(self):
    return  reverse('project_url', kwargs={'teamslug': self.teamslug,
                                           'projectslug': self.projectslug,
                                           'projectid': self.projectid,
                                           'teamid ': self.teamid,
    })
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top