首页 > 解决方案 > 终端上的表单数据显示&不保存在postgres数据库django中

问题描述

在我学习 django 的事业中,我决定从小项目开始,我正在制作一个简单的注册页面。我在主页 (index.html) 上有我的表单。我有一个 view.py 页面,我将表单中的所有数据传递到我的 postgres 数据库。我意识到数据不会保存在数据库中,而是所有注册数据都显示在终端和网址栏中。这是我的代码;

表单 (index.html)

<form action="/index/" method="POST">

              {% csrf_token %}

              <div><p><label for="fName">First Name</label></div>
                  <div><input type="text" name="fName"></input></div>
              </p>
              
              <p>
                  <label for="lName">Last Name</label>
                  <input type="text" name="lName"></input>
              </p>
              
              <p>
                  <label for="email">Email</label>
                  <input type="text" name="email"></input>
              </p>

              
                <div><p><label for="uName">Username</label></div>
                <div><input type="text" name="uName"></input></div>
              </p>
          
              <p>
                <label for="password1">Password</label>
                <input type="password" name="Password1"></input>
              </p>
              <p>
                <label for="password2">Confirm Password</label>
                <input type="password" name="Password2"></input>
              </p>

              <div> <p><input type="submit"></input></p> </div>
            
            </form>

视图.py

从 django.shortcuts 导入渲染,重定向

从 django.contrib.auth.models 导入用户,授权

def 索引(请求):

if request.method == 'POST':
    first_name = request.POST['fName']
    last_name = request.POST['lName']
    username = request.POST['uName']
    password1 = request.POST['password1']
    password2 = request.POST['password2']
    email = request.POST['email']
    
    
    
    user = User.objects.create_user(username=username, password=password1, email=email, 
    first_name=first_name, last_name=last_name)
    user.save()
    print('user created')
    return redirect('/')
else:

    return render(request, 'index.html')    

settings.py 上的数据库设置

数据库= {'默认':{

'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'bookconf',
            'USER': 'postgres',
            'PASSWORD': 'olumide',
            'HOST': 'localhost',
            'PORT': '5432',
}

}

我怀疑数据已被收集并且他们跳过执行此操作return render(request, 'index.html'),因为在我输入提交后,主页(index.html)被重新加载。

另外,我确定 psycopg2 已安装。除了以下消息外,没有数据保存在数据库中,也没有错误消息。

终端消息

[03/sep/2020 04:22:18]“ get/http/1.1” 200 25753 [03/sep/2020 04:22:37] =k.cole&Password1=1122&Password2=1122 HTTP/1.1" 200 25753

关于如何解决这个问题的想法将不胜感激。谢谢

标签: python-3.xdjango

解决方案


推荐阅读