简体   繁体   English

Django“使用参数反转____”…错误

[英]Django “reverse for ____ with arguments”… error

I'm receiving the following error 我收到以下错误

Error: Reverse for placeinterest with arguments ('',) and keyword arguments {} not found. 错误: placeinterest带有参数('',)和关键字参数{} placeinterest 1 pattern(s) tried: 尝试了1种模式:

[u'polls/(?P<section_id>[0-9]+)/placeinterest/$']

I worked through the Django example for a polling app, and now I'm trying to create a class registration app adapting what I already have. 我通过一个轮询应用程序的Django示例进行了研究,现在我正尝试创建一个适应现有功能的类注册应用程序。 Error points to line 5 here: 错误指向第5行:

<h1>{{ section.class_name }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:placeinterest' section.id %}" method="post">
{% csrf_token %}
<input type="radio" name="incr" id="incr" value="incr" />
<label for="incr"></label><br />
<input type="submit" value="Placeinterest" />
</form>

But I think the problem is in my placeinterest function: 但我认为问题出在我的placeinterest函数中:

def placeinterest(request, section_id):
    section = get_object_or_404(Section, pk=section_id)
    try:
        selected_choice = section.num_interested
    except (KeyError, Section.num_interested.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'section': section,
            'error_message': "You didn't select a choice.",
        })
    else:
        section.num_interested += 1
        section.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(section.id,)))

I'm not sure what my POST call should be if my Section class looks like this: 如果我的Section类看起来像这样,我不确定应该是什么POST调用:

class Section(models.Model):
    class_name = models.CharField(max_length=200)
    num_interested = models.IntegerField(default=0)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.class_name
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(minutes=3)
    def some_interested(self):
        if self.num_interested > 0:
            return "There is currently interest in this class"
        else:
            return "There is currently no interest in this class"

The results part comes up fine in my browser, and here is urls.py for good measure: 结果部分在我的浏览器中正常显示,下面是urls.py,可以很好地衡量:

from django.conf.urls import url

from . import views

app_name = 'polls'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<section_id>[0-9]+)/placeinterest/$', views.placeinterest, name='placeinterest'),
]

Edit: adding the original code from the example in hopes that might help someone see where I went wrong: 编辑:从示例中添加原始代码,希望可以帮助某人查看我出了什么问题:

urls: 网址:

from django.conf.urls import url

from . import views

app_name = 'polls'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]

vote function in views.py: views.py中的表决功能:

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

detail.html, where I'm having problems after making my changes: detail.html,进行更改后出现问题:

<h1>{{ question.question_text }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>

The error has nothing to do with your view. 该错误与您的视图无关。 It specifically says it's trying to match the URL named placeinterest in the error. 它专门表示正在尝试匹配错误中名为placeinterest的URL。 It knows the URL exists, but the arguments are wrong. 它知道URL存在,但是参数错误。

It thinks you're trying to pass an empty string as a positional argument. 它认为您正在尝试传递一个空字符串作为位置参数。 This means that section.id is probably None when the template is rendered. 这意味着呈现模板时, section.id可能为None It's converting the null value into an empty string and passing it as a positional argument, hence ('',) . 它将空值转换为空字符串,并将其作为位置参数传递,因此传递为('',) That's a tuple with one empty string value in it. 那是一个有一个空字符串值的元组。

The problem is here: 问题在这里:

<form action="{% url 'polls:placeinterest' section.id %}" method="post">

Django can't figure out the url argument as it's misconfigured. Django无法弄清楚url参数的配置错误。 Use this: 用这个:

<form action="{% url 'polls:placeinterest' section_id=section.id %}" method="post">

You also need to ensure that section id is valid a number (be careful of what you supply as "section" as your context. 您还需要确保部分ID是有效的数字(请注意您提供的"section"作为上下文)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django错误与参数&#39;(&#39;&#39;,)&#39;没有反向匹配 - Django error no reverse match with arguments '('',)' Django错误:反转参数“()”和关键字参数的“详细信息” - Django error: Reverse for 'details' with arguments '()' and keyword arguments 收到错误:在Django中使用参数&#39;(1,)&#39;反转&#39;update&#39; - Getting error : Reverse for 'update' with arguments '(1,)' in django django 错误:NoReverseMatch at /watchlist/ Reverse for &#39;viewList&#39; with arguments &#39;(&#39;&#39;,)&#39; - django error : NoReverseMatch at /watchlist/ Reverse for 'viewList' with arguments '('',)' 使用多个 arguments 反转 url 时出错 - Django - Error when reverse url with multiple arguments - Django Django NoReverseMatch错误,反向函数不带参数不起作用 - Django NoReverseMatch error, reverse function not work with no arguments Django NoReverseMatch错误找不到带有参数&#39;(&#39;&#39;,)&#39;和关键字参数&#39;{}&#39;的&#39;detail&#39;的反转 - Django NoReverseMatch error Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found django-allauth返回错误“反向…,未找到参数&#39;()&#39;和关键字参数&#39;{}&#39;” - django-allauth returns error “Reverse … with arguments '()' and keyword arguments '{}' not found” "Django 错误 - 带有参数 &#39;()&#39; 和关键字参数&#39;的&#39;password_reset_confirm&#39; 反向" - Django Error - Reverse for 'password_reset_confirm' with arguments '()' and keyword arguments ' Django url end href错误:反向为“”,参数为&#39;(&#39;,)&#39;和关键字参数为&#39;{}&#39; - Django url end href error: Reverse for '' with arguments '('',)' and keyword arguments '{}' not found
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM