清除输入字符串,而不使用django Form类 [英] Clean input strings without using the django Form classes

查看:163
本文介绍了清除输入字符串,而不使用django Form类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有推荐使用Django清理输入字符串而不通过Django表单系统的方法?

Is there a recommended way of using Django to clean an input string without going through the Django form system?

也就是说,我正在编写通过AJAX提供表单输入的代码,所以我正在跳过整个Form模型django的提供。但是我想在提交到数据库之前清理输入。

That is, I'm writing code that delivers form input via AJAX so I'm skipping the whole Form model django offers. But I do want to clean the input prior to submission to the database.

推荐答案

Django表单模型不仅仅是渲染表单,更多的是处理和清理表单(GET / POST)输入,其中 你想要做什么。当您的AJAX请求的POST或GET数据到达您的服务器时,它基本上与表单数据无法区分。我会主张创建一个表单模型,这是一个AJAX请求的模型。

Django Form models aren't just about rendering forms, they're more about processing and sanitizing form (GET/POST) input, which is what you want to do. When the POST or GET data from your AJAX request reaches your server it's essentially indistinguishable from form data. I would advocate creating a Form model that is a model of your AJAX request.

想想一个例子POST:

Think of an example POST:

POST /login.jsp HTTP/1.1
Host: www.mysite.com
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

userid=joe&password=guessme

这可能来自一个AJAX请求或一个表单,当它打到你的服务器它并不重要!当然,它们被称为表单模型,因为通常来自GET或POST数据的来源,但它不是来自一个表单:)

That could have come from an AJAX request OR a form, by the time it hits your server it doesn't really matter! Sure they're called Form models because that's usually where GET or POST data comes from, but it doesn't have to be from a form :)

如果您创建一个表单模型来表示您的AJAX请求,您将获得所有的钩子和消毒功能,它更多的是django-esque。

If you create a Form model to represent your AJAX request you get all the hooks and sanitization that come with it and it's all a little more "django-esque".

更新关于您的评论:

我想像你会有多个表单类。显然,我不知道你的系统是如何设计的,但是我会提供什么建议。

I imagine you'd have multiple form classes. Obviously I don't know how your system is designed, but I'll provide what advice I can.

像你说的一样,你会用这个来清理你的系统数据,所以你需要根据你发送的数据来定义你的Form类。例如,如果我有一个AJAX请求,提交一个名为,Email和CommentBody数据的注释,该数据将是一个Form类。如果我有另一个AJAX请求,发布一个新的文章,发送Title,Author和ArticleBody,这将是另一个Form类。

Like you said, you'll be using this to sanitize your data so you'll want to define your Form classes based on the data you're sending. For example, if I have an AJAX request that submits a comment with Name, Email and CommentBody data that would be one Form class. If I have another AJAX request that posts a new article that sends Title, Author and ArticleBody that would be another Form class.

并不是所有的AJAX请求都将需要一个Form如果你有一个AJAX电话来投票,你可能不会把它视为一个表单,因为(我猜测)你不需要清理任何数据。

Not all your AJAX requests will necessarily need a Form, if you have an AJAX call that votes up a comment you probably wouldn't treat that as a form, since (I'm guessing) you wouldn't need to sanitize any data.

这篇关于清除输入字符串,而不使用django Form类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆