cutejerry / SignSys

1 stars 0 forks source link

form checking #2

Open cutejerry opened 5 years ago

cutejerry commented 5 years ago

views.py

from django.shortcuts import render from SignModel.models import Course from SignModel.models import Record from django.http import HttpResponse from SignModel.forms import check_form

Create your views here.

def sign(request): course_list = list(Course.objects.all().order_by('name')) return render(request, 'sign.html', {'course_list': course_list})

def signfinish(request):

storage in database

if request.method == 'POST':
    form = check_form(request.POST)
    if form.is_valid():
        name = request.POST.get("name")
        grade = request.POST.get("grade_list")
        courses = request.POST.getlist("courses")
        phone_num = request.POST.get("phone_num")
        email = request.POST.get("email")
        (object, created) = Record.objects.get_or_create(name=name, grade=grade, phone_num=phone_num, email=email)
        if created == True:
            print(name, grade, courses, phone_num)
            for c in courses:
                obj = Course.objects.get(name=c)
                object.course_list.add(obj)
            object.save()
        else:
            print("The record is created.")
        return render(request, 'signfinish.html')
    else:
        print("**** invalid!! ****")
        return render(request, 'sign.html')
else:
    return render(request, 'signfinish.html') #for weichat flow

forms.py

from django import forms from django.core import validators from SignModel.models import Record

class check_form(forms.Form): phone_num = forms.CharField(validators=[validators.RegexValidator(r'^\d{3,11}$', message='请输入正确的电话号码')])

def clean_phone_num(self):
    phone_num = self.cleaned_data.get('phone_num')
    exists = Record.objects.filter(phone_num=phone_num).exists()
    if exists:
        raise forms.ValidationError(message='此电话号码已经被注册')
    return phone_num
cutejerry commented 5 years ago

https://blog.csdn.net/xujin0/article/details/84113013#t0