开发者

Clean input strings without using the django Form classes

开发者 https://www.devze.com 2022-12-10 16:40 出处:网络
Is there a recommended way of using Django to clean an input string without going through the Django form system?

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

That is, I'm writing code that delivers form input via AJAX so I'm sk开发者_C百科ipping the whole Form model django offers. But I do want to clean the input prior to submission to the database.


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.

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

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 :)

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".

Update regarding your comment:

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.

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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消