gpt4 book ai didi

python - 提交表单时HttpResponse不会显示 `post`信息

转载 作者:行者123 更新时间:2023-11-30 22:47:35 27 4
gpt4 key购买 nike

我正在通过 Django 工作,并且正在创建一个应用程序,该应用程序将允许用户使用 ID 号登录系统。所以我有两个 View ,一个供用户登录,另一个供用户注册。前一个 View 工作得很好,我可以让它显示用户提交的信息。但是我无法让第二个 View 向用户显示 POST 数据:

from .forms import NameForm, IdForm
from django.shortcuts import render
from django.http import HttpResponse

def sign_in(request):

if request.method == "POST":
#here will construct the form with the POST data
form = NameForm(request.POST)
#the next part is to check that the information submitted is valid
if form.is_valid():
post = form.save()
post.save()
return HttpResponse(post)
else:
return HttpResponse("Form is invalid")
else:
form = NameForm()
return render(request, 'checkin/base.html', {'form': form})



def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
return HttpResponse(post)
else:
return HttpResponse('Form is invalid')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})

基本上我想让回复是“谢谢,您的身份证号码是:post”。

这是我的模型的类:

from __future__ import unicode_literals

from django.db import models
from django import forms
from django.forms import ModelForm

# Create your models here.

class Question(models.Model):
question_text = models.CharField("What is your ID?", max_length=200)

id_text = models.CharField("Enter a new identification
number",max_length=200, null=True)

def __str__(self):
return self.question_text

以下是两个 View 的表单类:

from django.forms import ModelForm
from .models import Question

#put the form here

class NameForm(ModelForm):
class Meta:
model = Question
fields = ['question_text']

class IdForm(ModelForm):
class Meta:
model = Question
fields = ['id_text']

最佳答案

将 POST 数据显示为用户的响应通常是 Not Acceptable 。那不是 HTML,只是普通用户无法理解的字典。在 Django(实际上是几乎所有 Web 框架)中使用表单的标准方法是向用户显示表单验证错误,以便他可以纠正它。

正确的方法

def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
return HttpResponseRedirect('/succes_url')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})

关于python - 提交表单时HttpResponse不会显示 `post`信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40479391/

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