发帖问题

2024-06-28 11:38:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从django中的post获取值,但它传递了一个空字段`def PersonEmail(request):

我试图从django中的post获取值,但它传递了一个空字段`def PersonEmail(request):

if request.method == "POST":
    form1 = PersonForm(request.POST, prefix="form1")
    form2 = EmailForm(request.POST, prefix="form2")
    name = form2['email'].value
    return HttpResponse(name)
else:
    form1 = PersonForm()
    form2 = EmailForm()
    return render(request, 'CreatePersonEmail.html', locals())`

但当我把它们分开的时候

Im trying to get the value form a post in django but it pass an empty field `def PersonEmail(request):

if request.method == "POST":
    # form1 = PersonForm(request.POST, prefix="form1")
    form2 = EmailForm(request.POST, prefix="form2")
    name = form2['email'].value
    return HttpResponse(name)
else:
    form1 = PersonForm()
    form2 = EmailForm()
    return render(request, 'CreatePersonEmail.html', locals())`

它给了我字段的值。你知道吗

为什么?我怎样才能得到这两个表单域的值呢?你知道吗


Tags: djangonameprefixreturnvaluerequestdefpost
2条回答

在实例化表单时,需要同时使用前缀;在GET和POST时都需要使用前缀。你知道吗

另外,您可以从表单的cleaned_datadict获取值,而不是从字段获取值。你知道吗

基本上,你做错了。你知道吗

首先,你需要检查表格是否有效。用户可以输入任何废话,但你不想让他们这样做:

if request.method == "POST":
    form = MyForm(request.POST)
    if form.is_valid():
        # Now you can access the fields:
        name = form.cleaned_data['name']

如果表单无效,只需将其传递回render(),它就会显示错误。你知道吗

另外,不要这样做:

return render(request, 'CreatePersonEmail.html', locals())`

正确地建立你的上下文字典,不要使用locals(),它是黑客和你污染你的上下文。你知道吗

因此,完整视图可能如下所示(摘自django docs,稍作改动:

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            name = form.cleaned_data['name']
            return render(request, 'some_page.html', {'name': name})

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})

相关问题 更多 >