HttpResponse在提交表单时不会显示“post”信息

时间:2016-11-08 05:09:06

标签: python django forms post

我正在通过Django工作,我正在创建一个允许用户使用ID号登录系统的应用程序。所以我有两个视图,一个用于登录用户,另一个用于注册。前一个视图工作得很好,我可以让它显示用户提交的信息。但是,我无法获得第二个视图以向用户显示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})

基本上我想做出回复#34;谢谢你,你的身份证号码是: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 

以下是两个视图的表单类:

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']

2 个答案:

答案 0 :(得分:2)

将POST数据显示为用户的respnose通常是不可接受的。这不是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})

答案 1 :(得分:1)

问题在于返回HttpResponse(帖子),您正在将整个表单传递给HttpResponse,但正如您所提到的,您只需要 id_text 字段<强> IdForm 即可。 所以更新的代码应该是:

domain2.com/wp-admin/install.php