制作一个按钮,将您带到随机的下一页

时间:2018-05-16 03:59:44

标签: django django-templates django-views

所以我正在尝试使用Django制作一个测验应用。到目前为止,我有一个SQL数据库可以自动填充给定问题ID的模板。如果我转到http://localhost:8000/polls/2/,它会给我第二个测验问题。

我正在尝试制作一个按钮,在点击时会带我进行随机测验。

我在内部有以下方法:

# myproject/polls/view.py

def get_question_page(request, question_id):
    try:
        question = Question.objects.get(id=question_id)
    except Exception as e:
        question = None
    context = {'question': question}
    return render(request, 'index.html', context)

def get_random_page(request):
    n = Question.objects.count()
    rand = random.randint(1, n)
    return get_question_page(request, rand)

以下网址:

# myproject/polls/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P<question_id>[0-9]+)/$', views.get_question_page, name='question'),
    url(r'^rand/$', views.get_random_page, name='rand'),
    url(r'^(?P<question_id>[0-9]+)/select/$', views.select, name='select'),
]

我尝试在myproject/polls/index.html中使用以下代码:

<!-- myproject/polls/index.html -->

<form action="{% url 'views.get_random_page' %}" method="POST">
    <input id="submit"a type="button" value="Click" />
</form>

但我最终只得到:

NoReverseMatch at /polls/2/
Reverse for 'views.get_random_page' not found.
'views.get_random_page' is not a valid view function or pattern name.`

有人可以解释出现了什么问题以及如何解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

将app_name添加到您的urls.py

app_name = 'your_app_name'

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<question_id>[0-9]+)/$', views.get_question_page, name='question'),
url(r'^rand/$', views.get_random_page, name='rand'),
url(r'^(?P<question_id>[0-9]+)/select/$', views.select, name='select'),
]

以下面的格式添加网址,并将输入类型更改为提交以提交表单。

<form action="{% url 'your_app_name:rand' %}" method="POST">
    <input id="submit" type="submit" value="Click" />
</form>

答案 1 :(得分:0)

此视图get_random_page()返回的内容并不正确,您应该redirect('url_name')HttpResponseRedirect返回到传递的参数的相应网址,或直接返回HttpResponseRedirect('url_path') < / p>

而不是:

return get_question_page(request, rand)

尝试:

return redirect(get_question_page,question_id=rand)
# without quotes means, you call directly the function
# so the function should be above in order for python to find it.

return redirect("get_question_page",question_id=rand)
# With quotes, you actually call the url_name
# this is better, when you have to call views from other apps