1

我正在尝试制作一个页面,用户可以在其中键入他/她的消息并可以保存它。同时该页面还将显示其中的现有消息。

我无法保存消息。此处显示的消息已保存在 DB 中。

单击提交按钮后,会打开一个 Fobidden 页面,显示 CSRF 验证失败。请求中止。

请指导我在哪里做错了。

查看页面编码是:

# # Create your views here.

from django.http import HttpResponse
from home.models import dbmassage
from django.template import Context, loader


def index(request):

    #shows messages from the database
    home_message = dbmassage.objects.all()
    t = loader.get_template('C:/Users/NILESH/Desktop/Django-1.5.1/templates/home/index.html')
    c = Context({'home_message': home_message,})
    return HttpResponse(t.render(c))






    # handle submit message
    if request.method == 'POST':
        if request.POST['submit_action'] == 'Submit Message':
            # attempt to do submit
            b = home_message(request.POST)
        if b.is_valid():
            b.save()
            message = 'Message Submitted.'
        else:
            # validation failed: show submitted values in form
            f = submit_b
    return HttpResponse(t.render(c))


And the INDEX page coding I did is :

    <h1>The Messages</h1>


<h3>Type Your Message:</h3>
<form action='{{ request.path }}' method='POST'>
{% csrf_token %}
<input type="text" maxlength=80 style="width:300px">
<table>
{{ form }}
<tr>
  <td colspan=2 align=right>
    <h5>Maximum Length = 80</h5><input name="submit_action" type="submit" value="Submit Message">
  </td>
</tr>
</table>
</form>


<h3>The Existing Messages:</h3>
  {% if home_message %}
  <ul>
  {% for b in home_message %}
      <li>{{ b.massage }}</li>
  {% endfor %}
  </ul> 
  {% endif %}

并且 settings.py 代码只是中间件的事情::

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',

)

4

2 回答 2

4

您应该{% csrf_token %}form标签下添加这一行:

<form action='{{ request.path }}' method='POST'>
{% csrf_token %}
...

正如 Samuele 所说,你的代码永远不会到达下面的代码return HttpResponse(t.render(c))

视图可以重组为:

    #shows messages from the database
    home_message = dbmassage.objects.all()
    t = loader.get_template('C:/Users/NILESH/Desktop/Django-    1.5.1/templates/home/index.html')
    c = Context({'home_message': home_message,})

    # handle submit message
    if request.method == 'POST':
      if request.POST['submit_action'] == 'Submit Message':
        # attempt to do submit
        submit_b = home_message(request.POST)
        if submit_b.is_valid():
          submit_b.save()
          message = 'Message Submitted.'
        else:
          # validation failed: show submitted values in form
          f = submit_b
    return HttpResponse(t.render(c))

只需将return语句传递到方法的末尾即可。POST逻辑只会在表单提交后执行。

希望这可以帮助!

于 2013-06-12T17:09:27.117 回答
1

我调用 return 你的函数完成。我希望这段代码有帮助

in views.py
    def index(request):
        home_message = dbmassage.objects.all()
        if request.method == 'POST':
            form = YourForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data

            message = dbmassage(...call your dbmassage field like cd['message'] ...)
            message.save()


    else:
        form = Your Form()

    return render(request, 'your_template.html', {'form': form, 'home_message': home_message})

在模板中

<h1>The Messages</h1>


<h3>Type Your Message:</h3>
<form action='{{ request.path }}' method='POST'>
{% csrf_token %}
<input type="text" maxlength=80 style="width:300px">
<table>
{{ form }}
<tr>
  <td colspan=2 align=right>
    <h5>Maximum Length = 80</h5><input name="submit_action" type="submit" value="Submit Message">
  </td>
</tr>
</table>
</form>


<h3>The Existing Messages:</h3>
 {% if home_message %}
 <ul>
 {% for b in home_message %}
     <li>{{ b.massage }}</li>
 {% endfor %}
 </ul> 
 {% endif %}

在 form.py 中

class YourForm(forms.Form):
    message = forms.CharField()
于 2013-06-12T17:19:08.243 回答