Django - 模板内置过滤器标签{%url%}

时间:2017-10-21 21:47:30

标签: python django web backend

我是Django的新编码员。所以,如果这个问题太容易,请先道歉。

class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea)

def save_comments_into_database(topic, user_id, content):
    data = Comment(topic=topic, commenter_id=user_id, content=content)
    data.save()

这是表单的代码

<form action = "{% url 'post:comment' the_topic=topic user_id=1 %}" method="post">
        {% csrf_token %}
       {{ form.as_p }}
        <button type="submit">submit</button>
</form>

我正在尝试使用url标签来调用一个函数是views.py。 topic是我在创建此页面时传入的变量。

这是我在urls.py中的代码

url(r'^(?P<topic_id>[0-9]+)/comment/$', views.comment, name="comment"),

那么这就是我在views.py

中的表现
def comment(request, the_topic, user_id):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = CommentForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            text = form.cleaned_data['comment']
            args = {'form': form, 'text': text, 'topic': the_topic}
            # save the data in database
            save_comments_into_database(the_topic.id, user_id, text)
            # redirect to a new URL:
            return render(request, 'post/detail.html', args)

    # if a GET (or any other method) we'll create a blank form
    else:
        form = CommentForm()
        return render(request, 'post/detail.html', {'form': form, 'topic': the_topic})

我得到NoReserveMatchException: enter image description here

我真的不知道哪里出错了。

3 个答案:

答案 0 :(得分:0)

您应该更改声明网址,添加第二个参数并更改第一个

的名称
url(r'^(?P<the_topic>[0-9]+)/comment/(?P<user_id>[0-9]+)/$', views.comment, name="comment"),
#          ^^^^^^^^^                  ^^^^^^

答案 1 :(得分:0)

您的评论网址只有一个var topic_id,但您通过了两个变量the_topicuser_id。您只需要传递主题ID。此外,在视图中,您通常会通过request.user访问当前用户。

答案 2 :(得分:0)

最好使用在views.py中HttpResponseRedirect内置的Django来提供动作重定向,并将其与您的网址Django docs refreverse结合使用,检查以下内容并进行更改yourapp_path包含您的应用路径和name_space,网址名称为&#34;博客&#34;。

main urls.py with&#34; name_space&#34;

喜欢namepsace =&#34;博客&#34;

url(r'^', include('yourapp_path.urls', namespace='name_space))
#                  ^^^^^^^^^^^^                   ^^^^^^^^^^

app urls.py,名称=&#34;名称&#34;

喜欢名字=&#34;评论&#34;

url(r'^(?P<topic_id>[0-9]+)/comment/$', views.comment, name="name")
#                                                           ^^^^^^
带有name_space的

reverse:名称

将返回网址的完整路径name_space:name让我们说blog:comment

reverse('name_space:name')

与kwargs或args相反

reverse('name_space:name', kwargs={'kw1': 'val1'})
reverse('name_space:name', args=['val1'])

HttpResponseRedirect()

302重定向到给定网址,在这种情况下,我们将传递reverse网址。 喜欢:HttpResponseRedirect(反向(&#39;博客:评论&#39;,kwargs = {&#39; topic_id&#39;:topic.id}))

HttpResponseRedirect(reverse('name_space:name', kwargs={'kw1': 'val1'}))

views.py

#import HttpResoneRedircet and reverse
from django.shortcuts import HttpResponseRedirect, reverse
def comment(request, the_topic, user_id):
        # if this is a POST request we need to process the form data
    if request.method == 'POST':
            # create a form instance and populate it with data from the request:
            form = CommentForm(request.POST)
            # check whether it's valid:
            if form.is_valid():
                # your is_valid()
                return HttpResponseRedirect(reverse('name_space:name', kwargs={'the_topic': the_topic.id}))

模板

<form action="{{ action }}" method="post">
        {% csrf_token %}
       {{ form.as_p }}
        <button type="submit">submit</button>
</form>