gpt4 book ai didi

Django request.POST 作为表单的参数

转载 作者:行者123 更新时间:2023-12-02 06:40:10 26 4
gpt4 key购买 nike

我很难理解 request.POST 在以下示例中作为参数所做的事情:

def addauthorView(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['firstname']
last_name = form.cleaned_data['lastname']
user_email = form.cleaned_data['email']
c = AuthorModel(firstname=first_name, lastname=last_name, email=user_email)
c.save()
return HttpResponseRedirect('thanks/')
else:
form = ContactForm(request.POST)
return render(request, 'addauthor.html', {'form': form})

所以我知道这是可行的,但由于某种原因我无法理解 form = ContactForm(request.POST) 所发生的魔力。为什么 ContactForm 需要 request.POST 参数?幕后发生了什么?

额外的问题,为什么form = ContactForm(request.POST)然后在else: block 中重复。为什么它有用以及什么时候有用?例子?

最佳答案

简而言之,request.POST 就是 the data that was sent提交表格时。它是用户在代码示例中为 firstnamelastnameemail 提交的内容的字典。对于那些有 PHP 背景的人来说,这是 $_POST 中提供的内容。

form = ContactForm(request.POST) 将数据绑定(bind)到表单类,以便 Django 可以做一些有趣的事情,例如使用 is_valid() 验证输入。

为什么要将 request.POST 添加到 else: block 中?那么,您是否曾经向网站提交过表格,但出现错误时,您必须重新完整填写表格?这是一个糟糕的用户体验,对吧?通过将表单连同来自 request.POST 的数据发送回用户,您可以重新呈现用户输入的内容 - 以及有用的附加信息(例如错误消息) - 以便他们可以修复它们并重新提交。

编辑:要扩展,这里是 init method from the BaseForm class in Django :

def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, label_suffix=None,
empty_permitted=False):
self.is_bound = data is not None or files is not None
self.data = data or {}
self.files = files or {}
self.auto_id = auto_id
self.prefix = prefix
self.initial = initial or {}
self.error_class = error_class
# Translators: This is the default suffix added to form field labels
self.label_suffix = label_suffix if label_suffix is not None else _(':')
self.empty_permitted = empty_permitted
self._errors = None # Stores the errors after clean() has been called.
self._changed_data = None

# The base_fields class attribute is the *class-wide* definition of
# fields. Because a particular *instance* of the class might want to
# alter self.fields, we create self.fields here by copying base_fields.
# Instances should always modify self.fields; they should not modify
# self.base_fields.
self.fields = copy.deepcopy(self.base_fields)

当您将 request.POST 传递给表单类时,您实际上是在执行 data=request.POST。这反过来会触发 self.is_bound = True

关于Django request.POST 作为表单的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22524314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com