我正在尝试创建一个注册表单,但我注意到当我渲染 {{ form.as_p }}
时使用 UserCreationForm,将为用户显示所有可能的字段。现在有些字段,我只想由管理员访问。
所以,我知道可以通过fields=(f1,f2...)
来指定Meta Class中的字段
但是,即使从技术上讲这些字段并未显示在表单中,恶意用户是否仍然能够手动提交带有“ secret ”字段的 POST 请求?
我知道如何解决这个问题的唯一方法是手动验证每个字段并自己构建模型对象,以确保用户不会触及这些“ secret ”字段。怎么,这似乎违背了使用 UserCreationForm 的目的。有没有更好的办法?
仅供引用,当我的意思是破坏 UserCreationField 的目的时,我将无法使用 user = super(UserCreationForm,self).save(commit=True)
安全吗?
最佳答案
如果表单不知道该字段存在(即,它不在其元类的 fields
列表中),那么它不会在提交的表单中查找该字段的值数据。因此,您可以完全安全地保存表单中的数据。
举个例子,假设我们有以下模型:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField(blank=True, null=True)
hobbies = models.CharField(max_length=200, blank=True, null=True)
然后我们可以编写一个 LimitedCreateForm
,它只获取姓名和爱好,而不设置年龄。出于测试目的,我们可以在 View 中使用此表单,将提交的数据和相应创建的人员转储回浏览器以进行调试:
from django.shortcuts import render
from django import forms
from testapp.models import Person
class LimitedCreateForm(forms.ModelForm):
class Meta:
model = Person
fields = ('name', 'hobbies')
def create_limited(request):
submitted = ""
new_user = None
if request.method == 'POST':
submitted = str(request.POST)
form = LimitedCreateForm(request.POST)
if form.is_valid():
new_user = form.save()
else:
form = LimitedCreateForm()
data = {
'form': form,
'submitted': submitted,
'new_user': new_user,
}
return render(request, 'create_limited.html', data)
测试的最后一步是创建一个模板,该模板显示调试数据(表单中的 POST 数据和创建的相应人员),并创建一个“恶意”表单,其中包含年龄字段:
<html>
<body>
<h1>
Submitted data:
</h1>
<p>
{{ submitted|default:"Nothing submitted" }}
</p>
<h1>
Created user
</h1>
<p>
Name: {{ new_user.name|default:"Nothing" }}
<br />
Age: {{ new_user.age|default:"Nothing" }}
<br />
Hobbies: {{ new_user.hobbies|default:"Nothing" }}
</p>
<h1>
Form
</h1>
<form method="post">
{% csrf_token %}
Name: <input type="text" name="name" id="id_name">
<br />
Age: <input type="text" name="age" id="id_age">
<br />
Hobbies: <input type="text" name="hobbies" id="id_hobbies">
<br />
<input type="submit" value="Create" />
</form>
</body>
</html>
如果我们然后运行它并提交一些值,我们会得到以下调试输出:
提交的数据:
<QueryDict:
{u'age': [u'27'],
u'csrfmiddlewaretoken': [u'ed576dd024e98b4c1f99d29c64052c15'],
u'name': [u'Bruce'],
u'hobbies': [u'Dancing through fields of flowers']}>`
已创建用户
Name: Bruce
Age: Nothing
Hobbies: Dancing through fields of flowers
这表明表单忽略了提交的 27 岁年龄,只保存了被告知的字段。
值得注意的是,如果您指定要排除的字段列表(即 exclude = ('age',)
而不是 fields = ('name ', '爱好')
在表单元类中)。
关于python - Django 用户创建表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14176497/