【发布时间】:2023-04-09 05:51:01
【问题描述】:
如果用户不是 is_staff/is_superuser,则一直在尝试确定从 a 中删除字段的“最”优雅的解决方案。找到了一个有效的,代码量最少的。最初我想在“排除”元数据中添加“关闭”或使用两种不同的形式。但这似乎记录了正在发生的事情。逻辑在 '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
【问题讨论】:
标签: django forms django-class-based-views