Answers:
在视图中使用表单几乎可以解释这一点。
在视图中处理表单的标准模式如下所示:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
print form.cleaned_data['my_form_field_name']
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('contact.html', {
'form': form,
})
选择:
def my_view(request):
if request.method == 'POST':
print request.POST.get('my_field')
form = MyForm(request.POST)
print form['my_field'].value()
print form.data['my_field']
if form.is_valid():
print form.cleaned_data['my_field']
print form.instance.my_field
form.save()
print form.instance.id # now this one can access id/pk
注意:该字段可用时将立即对其进行访问。
form['my_field'].value()
,该解决方案用于在POST请求中访问表单值。几天:|
您可以在验证数据后执行此操作。
if myform.is_valid():
data = myform.cleaned_data
field = data['field']
另外,请阅读django文档。他们是完美的。
要从发送过帐请求的表单中检索数据,您可以像这样
def login_view(request):
if(request.POST):
login_data = request.POST.dict()
username = login_data.get("username")
password = login_data.get("password")
user_type = login_data.get("user_type")
print(user_type, username, password)
return HttpResponse("This is a post request")
else:
return render(request, "base.html")
class ContactForm(forms.Form): my_form_field_name = forms.CharField()