显然,当您通过表单保存数据时,您可以通过它的干净方法运行验证,但是如果您想在每次查看时重新验证该数据,您可以再次运行表单的清理方法吗?
我认为这个观点会沿着这个方向发展;
def detail(request, person_id=None):
"""
Renders an individual person
@param employer_id: The id of employer to view
@param request: HttpRequest
@return: HttpResponse
"""
person = get_object_or_404(People, pk=person_id)
validation_form = AddForm(instance=person)
is_valid = validate_person(validation_form)
return render_to_response(
'person/detail.html',
{
'is_valid': is_valid,
},
context_instance=RequestContext(request))
但是validate_person()
的“正确”方式是什么?
解决方案
我发现一个对象有一个.__dict__
方法,所以我的解决方案是;
form = AddForm(person.__dict__)
is_valid, errors = validate_person(form)
然后我的帮助函数可以返回表单是有效的,如果有则有错误;
def validate_person(form):
"""
Validate that the data stored for the person passes validation.
@param person: Person object
@param form: Form
@return: Boolean
"""
if form.is_valid():
return True, None
else:
return False, form.errors
现在我只需要在模板上找出一些列表理解来显示错误!
答案 0 :(得分:0)
是。你可以这样做。从person对象传递数据到PersonForm。参见示例。
form = PersonForm({'firstname':person.firstname,.....})
is_valid = form.is_valid()
答案 1 :(得分:0)
我认为你已经拥有的东西和Srinivas建议的东西可以合作:
def detail(request, person_id=None):
"""
Renders an individual person
@param employer_id: The id of employer to view
@param request: HttpRequest
@return: HttpResponse
"""
person = get_object_or_404(People, pk=person_id)
validation_form = AddForm(instance=person)
return render_to_response(
'person/detail.html',
{
'is_valid': validation_form.is_valid(),
},
context_instance=RequestContext(request))