cod*_*Joe 4 django django-forms
我有一个django形式的只读字段,我有时想编辑.
我只希望拥有正确权限的合适用户编辑该字段.在大多数情况下,该字段已锁定,但管理员可以对其进行编辑.
使用init函数,我可以将字段设置为只读,但不能选择只读.我还尝试将可选参数传递给StudentForm.初学但是变得比我想象的要困难得多.
有没有正确的方法来完成这个?
models.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 ...
Run Code Online (Sandbox Code Playgroud)
forms.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
Run Code Online (Sandbox Code Playgroud)
views.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))
Run Code Online (Sandbox Code Playgroud)
小智 8
那是你在找什么?通过稍微修改您的代码:
forms.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
Run Code Online (Sandbox Code Playgroud)
views.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))
Run Code Online (Sandbox Code Playgroud)
所以问题是检查视图级别的权限,然后在初始化时将参数传递给表单.现在,如果员工/管理员已登录,则字段将是可写的.如果不是,则只将类常量中的字段更改为只读.
| 归档时间: |
|
| 查看次数: |
6808 次 |
| 最近记录: |