一直在尝试确定"最"优雅的解决方案,如果用户不是is_staff/is_superuser,则从 from 中删除字段。 找到一个有效的,代码量最少。 最初,我试图在"排除"元中添加"关闭"或使用两种不同的形式。 但这似乎记录了正在发生的事情。 逻辑在"views.py"中,这是我觉得它所属的地方。
我的问题:这安全吗? 我还没有见过以这种方式操纵的形式,它有效。
models.py
class Update(models.Model):
denial = models.ForeignKey(Denial)
user = models.ForeignKey(User)
action = models.CharField(max_length=1, choices=ACTION_CHOICES)
notes = models.TextField(blank=True, null=True)
timestamp = models.DateTimeField(default=datetime.datetime.utcnow().replace(tzinfo=utc))
close = models.BooleanField(default=False)
forms.py
class UpdateForm(ModelForm):
class Meta:
model = Update
exclude = ['user', 'timestamp', 'denial', ]
views.py
class UpdateView(CreateView):
model = Update
form_class = UpdateForm
success_url = '/denials/'
template_name = 'denials/update_detail.html'
def get_form(self, form_class):
form = super(UpdateView, self).get_form(form_class)
if not self.request.user.is_staff:
form.fields.pop('close') # ordinary users cannot close tickets.
return form
是的,你的方法完全有效。FormMixin 旨在让您覆盖与在视图中管理表单相关的方法,并且测试起来很简单。
但是,如果您或其他人对生成的表单对象的动态修改变得过于广泛,则最好定义多个表单类并使用get_form_class()
来选择正确的表单类来实例化表单对象。