从 POST 请求获取 Django 值

我有以下 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()。每当单击“ Start”提交输入时,我希望“ Start”视图在返回呈现的页面之前使用函数中的 {{ source.title}}数据。如何将 POSTed (在本例中是隐藏输入)信息收集到 Python 变量中?

262715 次浏览

If you need to do something on the front end you can respond to the onsubmit event of your form. If you are just posting to admin/start you can access post variables in your view through the request object. request.POST which is a dictionary of post variables

Read about request objects that your views receive: https://docs.djangoproject.com/en/dev/ref/request-response/#httprequest-objects

Also your hidden field needs a reliable name and then a value:

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

Then in a view:

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

For django forms you can do this;

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))

You can use:

request.POST['title']

it will easily fetch the data with that title.