【问题标题】:How to use POST in Django如何在 Django 中使用 POST
【发布时间】:2018-02-17 00:44:03
【问题描述】:

我使用 Django 1.11.3 和 python2.7 我想写一个简单的留言板 这是我的代码

<form name='my form' action='/talkpost/' method='POST'>
    {% csrf_token %}
    {% for m in moods %}
    <input type='radio' name='mood' value='{{ m.status }}'>{{ m.status }}
    {% endfor %}
    <textarea name='user_post' rows=3 cols=70></textarea><br/>
    <label for='user_id'>nickname:</label>
    <input id='user_id' type='text' name='user_id'>
    <label for='user_pass'>password</label>
    <input id='user_pass' type='password' name='user_pass'><br/>
    <input type='submit' value='submit'>
    <input type='reset' value='reset'>
    <input type="hidden" name="ok" value="yes">
</form>

urls.py

url(r'^talkpost/', talkpost),
url(r'^talk/', talk),

talk 只供用户查看 from,talkpost 供 Django 获取帖子 请求

views.py

def talk(request):
    template = get_template('talk.html')
    moods = Mood.objects.all()
    message = 'Leave some message!'
    html = template.render(locals())
    return HttpResponse(html)

def talkpost(request):
    template = get_template('talk.html')
    if 'ok' in request.POST:
        user_id = request.POST['user_id']
        user_pass = request.POST['user_pass']
        user_post = request.POST['user_post']
        user_mood = request.POST['mood']
        message = 'success!'

    request_context = RequestContext(request)   
    request_context.push(locals())  
    html = template.render(request_context)
    return HttpResponse(html)

我尝试使用 {% csrf_token %} 和 RequestContext 但我仍然得到 CSRF 令牌丢失或不正确。 我不知道如何解决它

【问题讨论】:

  • 添加有问题的forms.py
  • 我没有使用 form.py

标签: html django python-2.7


【解决方案1】:

添加以下内容:

from django.views.decorators.csrf import csrf_protect

你的功能是:

@csrf_protect    
def talkpost(request):
    template = get_template('talk.html')
    if 'ok' in request.POST:
        user_id = request.POST['user_id']
        user_pass = request.POST['user_pass']
        user_post = request.POST['user_post']
        user_mood = request.POST['mood']
        message = 'success!'

    request_context = RequestContext(request)   
    request_context.push(locals())  
    html = template.render(request_context)
    return HttpResponse(html)    

更多信息在这里:

https://docs.djangoproject.com/ko/1.11/ref/csrf/#how-to-use-it

【讨论】:

  • 我尝试添加 @csrf_protect 但它仍然说 403 Forbidden CSRF token missing or wrong.
猜你喜欢
  • 2011-07-21
  • 2021-08-22
  • 2016-09-17
  • 2021-12-26
  • 1970-01-01
  • 2020-08-30
  • 2011-07-15
  • 2021-05-16
  • 2023-04-06
相关资源
最近更新 更多