请问各位,想引发一个这样的ValidationError异常要如何做?

cariana 2010-09-09 09:21:50
我用django做了个留言板应用

修改时在forms.py文件中多加了一个条件,在发信息时,如果指定收信息的人不是已注册的用户(该用户不存在),则引发一个ValidationError异常.



因为基础不深,只是参考了一下别的教程, 想出了两个方法,不过似乎都不太对,希望高手给指点一下,看看是哪里的问题.

第一种:
class MsgPostForm(forms.Form):

receiver=forms.CharField(label='Send to:',
widget=forms.TextInput (attrs={'size':30, 'max_length':30}))

#实例化一个用于输入留言标题的文本框对象,
#并将该对象保存到title属性中。
title=forms.CharField(label='Title',
widget=forms.TextInput (attrs={'size':30, 'max_length':30}))
#实例化一个用于输入留言内容的文本框对象,
#并将该对象保存到content属性中。
#该文本框会转换为tinymce富文本编辑器的外观。
content=forms.CharField(label='Content',
widget=forms.Textarea(attrs={'size':10000}))


#该函数用于验证用户输入receiver username的合法性
def clean_receiver(self):
if 'username' in self.cleaned_data:
#从通过一般性验证的用户名输入到指定的receiver文本框中
#并保存到变量receiver中
receiver=self.cleaned_data['receiver']
if receiver==username:
return receiver
#如果该用户不存在,则引发一个ValidationError异常
raise forms.ValidationError('This user does not exist.')



第二种:

class MsgPostForm(forms.Form):

receiver=forms.CharField(label='Send to:',max_length=30)
# receiver=forms.CharField(label='Send to:',
# widget=forms.TextInput (attrs={'size':30, 'max_length':30}))

#实例化一个用于输入留言标题的文本框对象,
#并将该对象保存到title属性中。
title=forms.CharField(label='Title',
widget=forms.TextInput (attrs={'size':30, 'max_length':30}))
#实例化一个用于输入留言内容的文本框对象,
#并将该对象保存到content属性中。
#该文本框会转换为tinymce富文本编辑器的外观。
content=forms.CharField(label='Content',
widget=forms.Textarea(attrs={'size':10000}))


#该函数用于验证用户输入receiver username的合法性
def clean_receiver(self):
if 'username' in self.cleaned_data:
receiver=self.cleaned_data['receiver']
try:
#从用户数据模型中取出username属性
#等于username变量值的用户对象
#如果在用户数据模型中不存在该用户对象
#则引发一个异常
User.objects.get(receiver!=username)
#异常处理
except ObjectDoesNotExist:
#返回username变量的值
return receiver
#如果用户两次输入的新密码不一致,则引发一个ValidationError异常
raise forms.ValidationError('This user does not exist.')


谢谢各位帮忙了!

...全文
1516 29 打赏 收藏 转发到动态 举报
写回复
用AI写文章
29 条回复
切换为时间正序
请发表友善的回复…
发表回复
qbever 2012-09-10
  • 打赏
  • 举报
回复
楼主是否用的是刘班老师讲的那个“基于Django快速开发网络留言板应用_”这篇文章?我也调试了很久,发现这个DJANGO的版本真是个问题。
notax 2010-09-17
  • 打赏
  • 举报
回复
分给amu 吧,

答了另外一题,不行没半法
送点资源分给我,现在很穷哦
cariana 2010-09-17
  • 打赏
  • 举报
回复
[Quote=引用 27 楼 notax 的回复:]
分给amu 吧,

答了另外一题,不行没半法
送点资源分给我,现在很穷哦
[/Quote]

好,这次一并把上次没给amu的分一起给了,呵呵

怎么分资源分呀?
notax 2010-09-16
  • 打赏
  • 举报
回复
冯客气,
姐你的嘴好甜哦,是个杀手
cariana 2010-09-16
  • 打赏
  • 举报
回复
[Quote=引用 25 楼 notax 的回复:]
冯客气,
姐你的嘴好甜哦,是个杀手
[/Quote]

请别人帮忙,这个态度是应该的~~

不好意思,再麻烦你一下下.

我另一个帖子没人回复了,现在问题还没解决.

就是当我点某个用户时,我想显示出该用户所有收到的留言列表.

而教程里只说了显示出所有该用户发出的留言.

原本的views.py是这样的

#导入get_object_or_404函数,
from django.shortcuts import get_object_or_404
def user_msg_list_page(request,username):
user=get_object_or_404(User,username=username)
return list_detail.object_list(
request,
queryset=user.msg_set.order_by('-id'),
paginate_by=ITEMS_PER_PAGE,
template_name='user_msg_list_page.html',
template_object_name='msg',
extra_context={'username':username}
)




得到这样的结果.

有人回帖说,若想实现显示出该用户所有"收到的"留言列表, 要用到这句:
queryset=get_object_or_404(msg_set,touser=user).order_by('-id')
#touser是外键收件人


可是不论我怎么改,都是错误提示:
"Global name 'msg_set' is not defined."


原帖在这里:
http://topic.csdn.net/u/20100909/22/e86ff2a2-b6c6-47b3-bd08-4985577cb892.html

如果你帮我回答,两个帖的分都给你~

谢谢啦~ *^_^*
cariana 2010-09-16
  • 打赏
  • 举报
回复
[Quote=引用 23 楼 notax 的回复:]
哦,客气了,
如果 用raise form.ValidationError('This user does not exist")
那is_valid就是False

再试试哦, 跟amu说的差不多吧


Python code

@login_required
def msg_post_page(request):
if request.method=='POST'……
[/Quote]

成功了~~~~~~~~~~

实在太感谢你了,一直以来都那么耐心!!!

对我这种新手来说真的是给了很大的帮助.

而且这还是我非常重要的毕业设计.

谢谢!!
notax 2010-09-15
  • 打赏
  • 举报
回复
哦,客气了,
如果 用raise form.ValidationError('This user does not exist")
那is_valid就是False

再试试哦, 跟amu说的差不多吧


@login_required
def msg_post_page(request):
if request.method=='POST':
form=MsgPostForm(request.POST)
if form.is_valid():
newmessage=Msg(title=form.cleaned_data['title'],
receiver = form.cleaned_data['receiver'],
content=form.cleaned_data['content'],
user=request.user,
ip=request.META['REMOTE_ADDR']
)
newmessage.save()
return HttpResponseRedirect('/')
else:
variables=RequestContext(request,{'form':form})
return render_to_response('msg_post_page.html',variables)
else:
form=MsgPostForm()
variables=RequestContext(request,{'form':form})
return render_to_response('msg_post_page.html',variables)
cariana 2010-09-15
  • 打赏
  • 举报
回复
实在太感谢楼上这位大大了~~~~~~~~~

眼泪淅沥哗啦的~~~~~~~~~

我验证过了,如果return "UNKNOWN USER"是没问题的.

可是根据客户要求,如果输入的是一个unknown user,就完全不返回值,在原页面返回一个validationError的提示.

象是这样:


可是,经过验证这个方式:

    def clean_receiver(self):
pprint.pprint(self.cleaned_data) # print self.cleaned_data
try:
User.objects.get(username = self.cleaned_data['receiver'])
return self.cleaned_data['receiver']
except User.DoesNotExist:
#return "UNKNOWN USER"
# if there is no such user, set self.cleaned_data['receiver'] to
# "UNKNOWN USER"

# or you can raised an exception error without returning "UNKNOWN USER"
# so that it wont be saved

raise forms.ValidationError('This user does not exist.')


不但什么都没返回,也没有ValidationError提示出现,页面直接跳回message list页.

cariana 2010-09-14
  • 打赏
  • 举报
回复
[Quote=引用 13 楼 notax 的回复:]
哦,原来amu已经答了,我还没看出来, 本来再想那 'msg_post_page.html',
'msg_detail_page.html','user_msg_list_page.html','registration/register.html' 来调试一下 ... ,
这样长的代码,不想打哦 ...
[/Quote]

可是我按照amu说的再改回去,就出现错误啊

"Global name 'username' is not defined."
notax 2010-09-14
  • 打赏
  • 举报
回复
哦,原来amu已经答了,我还没看出来, 本来再想那 'msg_post_page.html',
'msg_detail_page.html','user_msg_list_page.html','registration/register.html' 来调试一下 ... ,
这样长的代码,不想打哦 ...
cariana 2010-09-14
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 amu9900 的回复:]
将form验证方法clean_receiver里面的"username"换成"receiver"
你压根都没username传过来,判断"username"在不在cleaned_data里面有什么用?
我知道你为什么返回None了,因为if "username"条件不满足,又没写else,所以函数默认返回None

最后,你要再敢“无满意答案结贴”我就跟你拼了。。。

另外,你另一个“……
[/Quote]

啊,不好意思,我终于想起来那个无满意结帖是怎么回事了.

我是已经自己解决问题后一直都忘了结帖,过一段时间回来看后才发现你来帮忙,也不知道那根筋不对,就弄个无满意结帖,不好意思啊,以后不会了~~
cariana 2010-09-14
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 amu9900 的回复:]
将form验证方法clean_receiver里面的"username"换成"receiver"
你压根都没username传过来,判断"username"在不在cleaned_data里面有什么用?
我知道你为什么返回None了,因为if "username"条件不满足,又没写else,所以函数默认返回None

最后,你要再敢“无满意答案结贴”我就跟你拼了。。。

另外,你另一个“……
[/Quote]

啊~~~~ 不好意思啊~ 请息怒~~~

其实一开始我是和楼上写的一样的,可是总是出现错误:

amu9900 2010-09-14
  • 打赏
  • 举报
回复
将form验证方法clean_receiver里面的"username"换成"receiver"
你压根都没username传过来,判断"username"在不在cleaned_data里面有什么用?
我知道你为什么返回None了,因为if "username"条件不满足,又没写else,所以函数默认返回None

最后,你要再敢“无满意答案结贴”我就跟你拼了。。。

另外,你另一个“无满意答案结贴”的帖子我给你讲的东西貌似你还是没懂。

因为这个里面,同样的问题还存在。。到时候你发现这个问题解决了,错误信息居然还是显示。。。

解决这个问题了去看下您那个“无满意答案结贴”的帖子吧




#该函数用于验证用户输入receiver username的合法性
def clean_receiver(self):
#if 'username' in self.cleaned_data: #------这里错了---------
if 'receiver' in self.cleaned_data:
receiver=self.cleaned_data['receiver']
try:
#从用户数据模型中取出username属性
#等于username变量值的用户对象
#如果在用户数据模型中不存在该用户对象
#则引发一个异常
User.objects.get(receiver!=username)
#异常处理
except ObjectDoesNotExist:
#返回username变量的值
return receiver
#如果用户两次输入的新密码不一致,则引发一个ValidationError异常
raise forms.ValidationError('This user does not exist.')

amu9900 2010-09-14
  • 打赏
  • 举报
回复
你所谓的最后结果都是None是什么意思?
notax 2010-09-14
  • 打赏
  • 举报
回复
views.py


...

@login_required #decorator is above def msg_post_page
def msg_post_page(request):
if request.method=='POST':
form=MsgPostForm(request.POST)
if form.is_valid():
newmessage=Msg(title=form.cleaned_data['title'],
receiver = form.cleaned_data['receiver'],
content=form.cleaned_data['content'],
user=request.user,
ip=request.META['REMOTE_ADDR']
)
newmessage.save()
#
#else:
# you may need to handle the EXCEPTION here if the form is not valid,
# if Exception is raised from forms.ValidationError
return HttpResponseRedirect('/')

notax 2010-09-14
  • 打赏
  • 举报
回复

...
import pprint
class MsgPostForm(forms.Form):

receiver=forms.CharField(label='Send to:',max_length=30)
title=forms.CharField(label='Title',
widget=forms.TextInput (attrs={'size':30, 'max_length':30}))
content=forms.CharField(label='Content',
widget=forms.Textarea(attrs={'size':10000}))

def clean_receiver(self):
pprint.pprint(self.cleaned_data) # print self.cleaned_data
try:
User.objects.get(username = self.cleaned_data['receiver'])
return self.cleaned_data['receiver']
except User.DoesNotExist:
return "UNKNOWN USER"
# if there is no such user, set self.cleaned_data['receiver'] to
# "UNKNOWN USER"

# or you can raised an exception error without returning "UNKNOWN USER"
# so that it wont be saved

#raise forms.ValidationError('This user does not exist.')
raise forms.ValidationError('This user does not exist.')


def clean(self):
pprint.pprint(self.cleaned_data)
if 'username' in self.cleaned_data and 'receiver' in self.cleaned_data:
if self.cleaned_data['username'] == self.cleaned_data['receiver']:
raise forms.ValidationError('user = receiver ')
return self.cleaned_data




views.py

[code=Python]
...

@login_required #decorator is above "def msg_post_page"
def msg_post_page(request):
if request.method=='POST':
form=MsgPostForm(request.POST)
if form.is_valid():
newmessage=Msg(title=form.cleaned_data['title'],
receiver = form.cleaned_data['receiver'],
content=form.cleaned_data['content'],
user=request.user,
ip=request.META['REMOTE_ADDR']
)
newmessage.save()
#
#else:
# you may need to handle the EXCEPTION here if the form is not valid,
# if Exception is raised from forms.ValidationError
return HttpResponseRedirect('/')

[code]
cariana 2010-09-14
  • 打赏
  • 举报
回复
msg_list.html:

<tr align="center">
<th>Title</th><th>Sender</th>
<th>Date</th><th>Hits</th><th>Send to</th>
</tr>
<! --If the value of msg_list is NOT-NULL-->
{% if msg_list %}
<! --Load comments of Django-->
{% load comments %}
<! --From the message list saved in msg_list,use for loop and save into msg variable-->
{% for msg in msg_list %}
<tr align="center">
<td align="left">
<! --{{msg.id}}is used for saving the value of id-->
<a href="/detail/{{msg.id}}/">
<! --Retrieve the title-->
{{msg.title}}
</a>
</td>
<! --{{msg.user.username}}is used for retrieving the sender's name-->
<td><a href="/user/{{msg.user.username}}/">{{msg.user.username}}</a></td>

<! --Retrieve the submition time,and format it-->
<td>{{msg.datetime|date:"Y-m-d"}}</td>
<! --Retrieve the number of click-->
<td>{{msg.clickcount}}</td>


<! --{{msg.receiver}}is used for retrieving the receiver's name-->
<td><a href="/user/{{msg.receiver}}/">{{msg.receiver}}</a></td>

</td>
</tr>

{% endfor %}
{% else %}
<tr align="center"><td colspan="8">No message!
</td></tr>
{% endif %}



notax 2010-09-14
  • 打赏
  • 举报
回复
+ msg_list.html
cariana 2010-09-14
  • 打赏
  • 举报
回复
'msg_list_page.html':

<! --This file will be saved by utf8-->
<! --此模板从基础模板base.html继承-->
{% extends "base.html"%}
<! --对基础模板中的block title,endblock部分进行修改-->
{% block title %}Message List{% endblock %}
<! --对基础模板中的block content,endblock部分进行修改-->
{% block content %}
<table class="msglist">
<caption><h2>Primesoft Message Board</h2></caption>
<! --JIANG msg_list.html MOBAN BAOHAN DAO BEN MOBAN ZHONG-->
{% include "msg_list.html" %}
</table>
<! --JIANG paginator.html MOBAN BAOHAN DAO BEN MOBAN ZHONG-->
{% include "paginator.html" %}
{% endblock %}



'registration/register.html':
<! --This file will be saved by utf8-->

{% extends "base.html" %}

{% block title %}User Registration{% endblock %}

<! --对基础模板中的block head,endblock部分进行修改-->
{% block head %}User Registration{% endblock %}

{% block content %}


<! --action 属性指定由 register_page 函数负责处理该表单用post 方法提交的数据-->
<form method="post" action=".">{% csrf_token %}


{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}



<! --利用从register_page 函数传递过来的注册表单对象form 生成描述注册表单包含的各个表单元素的 html代码-->
{{form.as_p}}

<input type="submit" value="Register">

</form>
{% endblock %}



'msg_post_page.html':
{% extends "base.html" %}

{% block title %}Post Message{% endblock %}

{% block head %}Post Message{% endblock %}

{% block content %}
<form method="post" action=".">{% csrf_token %}
<! --利用从 msg_post_page 函数传递过来的留言表单对象form 生成描述发表留言表单包含的各个表单元素的 html代码-->
{{form.as_p}}
<input type="submit" value="Submit">
</form>

{% endblock %}



'msg_detail_page.html':
{% extends "base.html" %}

{% load comments %}

{% block title %}Message content and comments{% endblock %}

{% block head %}Message content and comments{% endblock %}

{% block content %}
<table class="msglist">
<tr align="left">
<th>Sender:{{msg.user.username}}</th>
<th>Send to:{{msg.receiver}}</th>
<th>Date:{{msg.datetime|date:"Y-m-d"}}</th>


</tr>
<tr>
<td colspan="4"><b>{{msg.title}}</b></td>
</tr>
<tr>
<! --Retrieve the detail of message-->
<td colspan="4">{{msg.content}}</td>
</tr>
</table>

{% endblock %}



'user_msg_list_page.html':


{% extends "base.html"%}
{% load comments %}

<! -- -username- 用于去除从object_list函数传递过来的username模板变量的值-->

{% block title %}{{username}}'s Message List{% endblock %}

{% block content %}
<table class="msglist">
<caption><h2>{{username}}'s Message List</h2></caption>

{% include "msg_list.html" %}
</table>

{% include "paginator.html" %}
{% endblock %}



base.html:

<! --This file will be saved by utf8-->
<html>
<head>
<title>Primesoft Message Board|{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="/site_media/style.css" type="text/css">
<! --Install tinymce-->
<script type="text/javascript" src="/site_media/tiny_mce.js"></script>
<! --Initial tinymce -->
<script type="text/javascript">
tinyMCE.init({
mode:"textareas",
theme:"advanced",
<! --Define using the emotions plugin of tinymce-->
plugins:"emotions",
<! --Define tinymce buttons-->
theme_advanced_buttons1:"bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect",
theme_advanced_buttons2:"cut,copy,paste,|,undo,redo,|,forecolor,backcolor,|,emotions",
theme_advanced_buttons3:"",
<! --Define timynce location-->
theme_advanced_toolbar_location:"top",
<! --Define tinymce align-->
theme_advanced_toolbar_align:"left",
<! --Define timymce language-->
language:"En"
});
</script>
</head>

<body>
<! --html marked by div discribes the navigation bar-->
<div class="nav">
<a href="/">Homepage|</a>
<a href="/post/">Post Message|</a>
{% if user.is_authenticated %}
<a href="/user/{{ser.username}}/">
{{user.username}}|</a>
<a href="/accounts/password/change/">Change Password|</a>
<a href="/accounts/logout/">Logout|</a>
{% else %}
<a href="/accounts/login/?next=/">Login|</a>
<a href="/accounts/register/">Register|</a>
{% endif %}
<a href="/admin/">Admin</a>
</div>
<h4>{% block head %}{% endblock %}</h4>
{% block content %}{% endblock %}
</body>
</html>


notax 2010-09-14
  • 打赏
  • 举报
回复
'msg_list_page.html',
'registration/register.html'
'msg_post_page.html'
'msg_detail_page.html',
'user_msg_list_page.html',

+ base.html
加载更多回复(8)

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧