开发者

Is there another way to create a more secure form in django

I have a paranoia about using hiddenfield in modelform for foreignkeys. I initialize the value before I send the form to user for foreignkeys and hide them and when a user sends back values by post, I just save the form 开发者_运维问答with basic validation. Can anyone change data in hidden form fields for malicious reasons, or change data and change data in another one row? Is there another secure way?

model:

class company(models.Model):
user=models.ForeignKey(User)
comname=models.CharField(max_length=255)
regcode=models.CharField(max_length=128,blank=True,null=True)

froms:

class companyform(forms.ModelForm):

comname=forms.CharField(label=_("company name"),help_text=_("This name appear on top of forms and printed content"))

regcode=forms.CharField(label=_("Register code "),help_text=_("Registered code of organization in goverment"))

class Meta: 
    model=careunitgeneralsetting
    exclude = ('user',)

view:

return render_to_response("home_them.html",{"form":unicode(companyform(initial="user":request.user.id)},context_instance=RequestContext(request))


I assume you want to set company.user to one currenlty logged in and prevent it from being changed. You're doing it almost right:

  1. Field is excluded from form as it should be. In the long run, however, it's safer to use fields (whitelist) than exclude (blacklist) in form declarations. This prevents unexpected side effects when fields are added to model in question.

  2. Initial value for user should be provided, but there's a better way -- leverage the fact that ModelForm is used:

    {"form": CompanyForm(instance=Company(user=request.user))


You should never depend on a browser to send you appropriate data. Remember it's not a browser that is the interface of your web application - HTTP / another protocol is. It'll be always possible to build a form that is specifically crafted to send you some malformed data. Even better - someone could just open a telnet terminal and type in anything.

Any data that comes from the outside should be considered untrusted and should be validated on the server. Client side validation is only a convenient feature for the user, never a security measure.

In Django forms are used for server side validation. However you cannot partition the validation process and assume that once data has been validated it can be transmitted back and forth between client and server and still remains that way. If you want to ensure that certain values remain unchanged in the course of several requests use session variables that live on the server side and therefore cannot be tampered with.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜