一分钟学会Django的表单

8 篇文章 0 订阅
7 篇文章 0 订阅
#forms.py 

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField()
    email = forms.EmailField(required=False, label='Your e-mail address') #define label
    message = forms.CharField(widget=forms.Textarea ) #define output format  
	
	#define custom check method, nameing rule clean_attname(), executed after default clean(),e.g, is_valid() method. 
	#we can set cleand_data to the python value we want, so the value is better returned or we will lost the value. 
	
	def clean_message(self):         
		message = self.cleaned_data['message']        
		num_words = len(message.split())        
		if num_words < 4:            
			raise forms.ValidationError("Not enough words!")        
		return message


# views.py

from django.shortcuts import render_to_response
from mysite.contact.forms import ContactForm

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():   #if valid, then cleaned_data attr is gen.
            cd = form.cleaned_data
            send_mail(
                cd['subject'],
                cd['message'],
                cd.get('email', 'noreply@example.com'),
                ['siteowner@example.com'],
            )
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm()         #or add an initial value          
		form = ContactForm(initial={'subject': 'I love your site!'})
    return render_to_response('contact_form.html', {'form': form})

# contact_form.html

<html> 
	<head>    
		<title>Contact us</title>    
		<style type="text/css">     
			ul.errorlist {        
				margin: 0;       
				padding: 0;}    
			.errorlist li {       
				background-color: red;        
				color: white;        
				display: block;        
				font-size: 10px;        
				margin: 0 0 3px;       
				padding: 4px 5px;}   
		</style>
	</head>
	<body>    
		<h1>Contact us</h1>     
		{% if form.errors %}        
			<p style="color: red;">            
			Please correct the error{{ form.errors|pluralize }} below.        
			</p>    
		{% endif %}     
		
		<form action="" method="post">       
			<div class="field"> #define you own style            
				{{ form.subject.errors }}            
				<label for="id_subject">Subject:</label>            
				{{ form.subject }}        
			</div>        
			<div class="field">            
				{{ form.email.errors }}            
				<label for="id_email">Your e-mail address:</label>            
				{{ form.email }}       
			</div>       
			<div class="field">            
				{{ form.message.errors }}            
				<label for="id_message">Message:</label>            
				{{ form.message }}        
			</div>        
			<input type="submit" value="Submit">    
		</form>    
		
		<!--{{ form.message.errors }} 会在 <ul class="errorlist"> 里面显示,如果字段是合法的,或者form没有被绑定,就显示一个空字符串。--> 
		<!-- 我们还可以把 form.message.errors 当作一个布尔值或者当它是list在上面做迭代, 例如:-->
		
		<div class="field{% if form.message.errors %} errors{% endif %}">    
			{% if form.message.errors %}        
			<ul>        
				{% for error in form.message.errors %}            
				<li><strong>{{ error }}</strong></li>        
				{% endfor %}        
			</ul>    
			{% endif %}    
			<label for="id_message">Message:</label>    
			{{ form.message }}
		</div>
		
		<!--在校验失败的情况下, 这段代码会在包含错误字段的div的class属性中增加一个”errors”,在一个有序列表中显示错误信息。-->
	</body>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值