我在 django 表单中有一个只读字段,有时我想编辑它。
我只想要具有正确权限的正确用户来编辑该字段。在大多数情况下,该字段被锁定,但管理员可以对其进行编辑。
使用 初始化 功能,我可以将该字段设为只读或不设为只读,但不能选择设为只读。我还尝试将可选参数传递给 StudentForm。 初始化 但这比我预期的要困难得多。
有没有合适的方法来做到这一点?
模型.py
class Student():
# is already assigned, but needs to be unique
# only privelidged user should change.
student_id = models.CharField(max_length=20, primary_key=True)
last_name = models.CharField(max_length=30)
first_name = models.CharField(max_length=30)
# ... other fields ...
表格.py
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ('student_id', 'last_name', 'first_name',
# ... other fields ...
def __init__(self, *args, **kwargs):
super(StudentForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance:
self.fields['student_id'].widget.attrs['readonly'] = True
View .py
def new_student_view(request):
form = StudentForm()
# Test for user privelige, and disable
form.fields['student_id'].widget.attrs['readonly'] = False
c = {'form':form}
return render_to_response('app/edit_student.html', c, context_instance=RequestContext(request))
最佳答案
这就是你要找的吗?通过稍微修改您的代码:
表格.py
class StudentForm(forms.ModelForm):
READONLY_FIELDS = ('student_id', 'last_name')
class Meta:
model = Student
fields = ('student_id', 'last_name', 'first_name')
def __init__(self, readonly_form=False, *args, **kwargs):
super(StudentForm, self).__init__(*args, **kwargs)
if readonly_form:
for field in self.READONLY_FIELDS:
self.fields[field].widget.attrs['readonly'] = True
View .py
def new_student_view(request):
if request.user.is_staff:
form = StudentForm()
else:
form = StudentForm(readonly_form=True)
extra_context = {'form': form}
return render_to_response('forms_cases/edit_student.html', extra_context, context_instance=RequestContext(request))
所以事情是检查 View 级别的权限,然后在初始化时将参数传递给您的表单。现在,如果员工/管理员登录,字段将是可写的。如果不是,则只有类常量中的字段将更改为只读。
关于django - 如何在 Django 表单中创建可选的只读字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4485561/