Django - 从POST请求获取值

时间:2012-07-05 00:11:59

标签: python django post

我有以下django模板(http:// IP / admin / start /分配给一个名为view的假想视图):

{% for source in sources %}
  <tr>
    <td>{{ source }}</td>

    <td>
    <form action="/admin/start/" method="post">
      {% csrf_token %}
      <input type="hidden" name="{{ source.title }}">
      <input type="submit" value="Start" class="btn btn-primary">
    </form>
    </td>

  </tr>
{% endfor %}

sources是视图中引用的Django模型的objects.all()。每当单击“开始”提交输入时,我希望“开始”视图在返回呈现页面之前使用函数中的{{ source.title}}数据。如何将信息POST(在本例中为隐藏输入)收集到Python变量中?

3 个答案:

答案 0 :(得分:104)

了解您的观看次数所接收的请求对象:https://docs.djangoproject.com/en/dev/ref/request-response/#httprequest-objects

此外,您的隐藏字段需要一个可靠的名称,然后是一个值:

<input type="hidden" name="title" value="{{ source.title }}">

然后在视图中:

request.POST.get("title", "")

答案 1 :(得分:11)

如果您需要在前端执行某些操作,则可以响应表单的onsubmit事件。如果您只是发布到admin / start,则可以通过请求对象访问视图中的post变量。 request.POST这是一个后期变量字典

答案 2 :(得分:2)

对于Django表单,您可以执行此操作;

form = UserLoginForm(data=request.POST) #getting the whole data from the user.
user = form.save() #saving the details obtained from the user.
username = user.cleaned_data.get("username") #where "username" in parenthesis is the name of the Charfield (the variale name i.e, username = forms.Charfield(max_length=64))