Django NoReverseMatch url issue

2019-08-15 18:21发布

问题:

I'm getting the error

"Reverse for 'recall' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'associate/recall/']"

When I try to submit a form. Here is my html:

    <form action="{% url 'associate:recall' ordered_group %}" method="post">
        {% csrf_token %}

        <div>
            <label for="recall">enter as many members of {{ ordered_group }} as you can recall </label>
            <input type="text" id="recall" name="recall">
        </div>
        <div id="enter_button">
            <input type="submit" value="enter" name="enter" />
        </div>
        <div id="done_button">
            <input type="submit" value="done" name="done" />
        </div>
    </form>

"ordered_group" is a model object that is carried over from the 'learn' view:

urls.py:

urlpatterns = patterns('',
    url(r'^learn/', "associate.views.learn", name='learn'),
    url(r'^recall/', 'associate.views.recall', name='recall'),
    url(r'^$', "associate.views.index", name='index'),
)

I am trying to use the ordered_group model object that is submitted in the learn view context to the html, back to the recall view as an argument. Can one do this? It makes sense to me, but what is the correct way of doing this?

views.py

def recall(request, ordered_group):
  ...


def learn(request):
... 
ordered_group = ordered_groups[index]

 return render(request, 'associate/learn.html', {'dataset':model, 'ordered_group':ordered_group})

I want to submit the form with

回答1:

In you HTML, you are doing:

{% url 'associate:recall' ordered_group %}

Django expects that "recall" url is in "associate" namespace, because of the ":". But, you need to declare the namespace in urls.py, like:

url(r'^recall/', 'associate.views.recall', namespace='associate', name='recall')

If you don't want the namespace, just do:

{% url 'recall' ordered_group %}

And, about "ordered_group", you need to declare it in your url, like:

url(r'^recall/(?P<ordered_group>\w+)', 'associate.views.recall', namespace='associate', name='recall')

You are passing ordered_group in HTML, youare expecting this in views.py, but you are not expecting this on you URL.