3

我有这个表格:

<form action="{% url create_question %}" method="post">

而这个 url.py

url(r'^neues_thema/(\w+)/','home.views.create_question',name="create_question"),

但我收到此错误:

Reverse for 'create_question' with arguments '()'
 and keyword arguments '{}' not found.

我究竟做错了什么?

编辑:我想做的是:用户提交表单,我想获取用户正在创建的问题的标题并将其放入 url。然后 url 看起来像:neues_thema/how-to-make-bread/. 如何{% url create_question ??? %}在提交表单时动态地提供该参数

django 模板中的这个线程url 模板标签对我没有帮助。

4

4 回答 4

3

您的 url 正则表达式需要一个参数,您的模板应如下所示:

<form action="{% url create_question some_user_name %}" method="post">

请参阅内置模板标签和过滤器文档中的url

于 2013-05-25T17:50:16.463 回答
2

你可以做:

url(r'^neues_thema/(?P<user>\w*)$','home.views.create_question',name="create_question"),

在你看来

def create_question(request, user=None):
于 2013-05-25T17:56:14.237 回答
1

似乎您的模板中不需要任何参数{% url %}

You can add function to your views.py for creating questions, that will redirect user to question page after success:

urls.py:

url(r'^neues_thema/', 'home.views.create_question', name="create_question"),
url(r'^neues_thema/(?P<title>\w+)/', 'home.views.question', name="question"),

views.py:

from django.core.urlresolvers import reverse
from django.shortcuts import render

def create_question(request):
    if request.method == 'POST':
        title = request.POST['title']
        # some validation of title
        # create new question with title
        return redirect(reverse('question', kwargs={'title': title})


def question(request, title):
    # here smth like: 
    # question = get_object_or_404(Question, title=title)
    return render(request, 'question.html', {'question': question})

template with form for creating question:

<form action="{% url create_question %}" method="post">

Answering your "what am i doing wrong?". You are trying to render url by mask neues_thema/(\w+)/ with this: {% url create_question %}. Your mask needs some parameter ((\w+)), but you are putting no parameter. Rendering with parameter should be {% url create_question title %}. But the problem is: you don't know the title while rendering page.

于 2013-05-25T18:48:20.867 回答
0

像这样写{% url 'home.views.create_question' alhphanumeric_work %}。它应该工作。

于 2013-05-25T18:27:20.803 回答