如何使用Django

时间:2019-03-17 16:14:00

标签: django

我是第一次学习django。这是我要提交的表单数据  数据库,代码运行良好。

这是我的 views.py

from django.shortcuts import render, redirect, HttpResponseRedirect
from .models import Member

# Create your views here.
#proces form data
def index(request):
    if request.method == 'POST':
        member = Member(username=request.POST['username'], password=request.POST['password'], confirmPassword=request.POST['confirmPassword'], email=request.POST['email'])
        member.save()
        return redirect('/')
    else:
        return render(request, 'web/index.html')

这是 models.py

from django.db import models
# Create your models here.
class Member(models.Model):
    username=models.CharField(max_length=30)
    password=models.CharField(max_length=12)
    confirmPassword=models.CharField(max_length=12)
     email=models.CharField(max_length=30)

    def __str__(self):
        return self.username + " " + self.email

这是index.html

{% extends 'web/base.html' %}
{% block body %}
<form method="POST">
    {% csrf_token %}

            <input type="text" name="username" id="username"/>
            <input type="password" name="password" id="password"/>
            <input type="password" name="confirmPassword" id="confirmPassword"/>
            <input type="text" name="email" id="email"/>

            <button type="submit"> Submit</button>
</form>
{% endblock %}

这是我要添加的内容:

现在,我想使用 cleaned_data [] 方法在提交之前验证数据,并检查密码并确认 提交表单前密码已匹配,但出现以下错误

identationError;希望有一个已识别的块。  我引用了此处找到的解决方案,但没有运气link

这就是我为此目的所尝试的。

有人可以帮我吗...

#proces form data
def index(request):
    if request.method == 'POST':

uname = request.cleaned_data['username']
pass = request.cleaned_data['password']
confirmPass = request.cleaned_data['confirmPassword']
email = request.cleaned_data['email']

if pass != confirmPass:

context = {'msg': 'Passwords does not match'}
return render(request, 'web/error.html', context)
#insert records if things were okay

        member = Member(username=uname, password=pass, confirmPassword=confirmPass, email=email)
        member.save()
        return redirect('/')
    else:
        return render(request, 'web/index.html')

1 个答案:

答案 0 :(得分:0)

要使用data_clean()方法,我要做的是创建一个 forms.py 并将其导入 views.py

这是 forms.py 的外观

from django import forms

class signupForm(forms.Form):

    username = forms.CharField(max_length=30)
    password = forms.CharField(max_length=12)
    confirmPassword=forms.CharField(max_length=12)
    email=forms.CharField(max_length=30)

class loginForm(forms.Form):

    username = forms.CharField(max_length=30)
    password = forms.CharField(max_length=12)