美文网首页
6(just form no database)

6(just form no database)

作者: EudeMo | 来源:发表于2015-11-12 21:43 被阅读0次

    添加一个不需要写入数据库的表单contact

    1. 在forms.py中添加contact类
    class ContactForm(forms.Form):
        name = forms.CharField(max_length=120)
        email = forms.EmailField()
        phonenumber = forms.CharField(max_length=20)
        def clean_email(self):
            email = self.cleaned_data.get('email')
            email_base, email_provider = email.split("@")
            email_domain, email_extension = email_provider.split('.')
            print(email_base, email_provider, email_domain, email_extension)
            if not email_domain == '163':
                raise forms.ValidationError("you should input 163 email")
            return email #实际上被写入的email的值
    
    1. 在views.py里添加如下代码:
    def contact(request):
        form = ContactForm(request.POST or None)
        title = "hi contact"
        if form.is_valid():
            for key,value in form.cleaned_data.items():#python2.7使用iteritems()
                print(key,value)
        context = {
            'form':form,
            'title':title,
        }
        return render(request, 'contact.html', context)
    
    1. 在templates文件夹下面添加contract.html文件
    <h1>{{ title }}</h1>
    <form method="POST" action=""> {% csrf_token %}
        {{ form.as_p }}<!-- as_p的作用是让他按行显示,而不是显示在一行 -->
        <input type="submit" value="submit">
    </form>
    

    相关文章

      网友评论

          本文标题:6(just form no database)

          本文链接:https://www.haomeiwen.com/subject/pqohhttx.html