django中的强制性只读字段 [英] Mandatory read-only fields in django
问题描述
class Student(models.Model):
name = models.CharField(max_length = 50)
parent = models.CharField(max_length = 50)
def __unicode __(self):
return self.name
class Grade(models.Model):
studentId = models.ForeignKey(学生)
finalGrade = models.CharField(max_length = 3)
I '我希望能够改变一个模型中的几个学生的最终成绩,但现在我只是一次尝试一个学生。我也试图为它创建一个表单,将学生名称显示为无法更改的字段,这里唯一可以改变的是finalGrade。所以我用这个技巧让studentId成为只读的。
class GradeROForm(ModelForm):
studentId = forms.ModelChoiceField(queryset = Student.objects.all())
def __init __(self,* args,** kwargs):
super(GradeROForm,self).__ init __(* args,** kwargs)
instance = getattr(self,'instance' ,无)
如果instance和instance.id:
self.fields ['studentId']。widget.attrs ['disabled'] ='disabled'
def clean_studentId(self):
instance = getattr(self,'instance',None)
if instance:
return instance.studentId
else:
return self.cleaned_data.get('studentId' ,无)
class Meta:
model = Grade
这里是我的查看:
def modifyGrade(request,student):
student = Student.objects.get(name = student)
mygrade = Grade.objects.get(studentId = student)
如果request.method ==POST:
myform = GradeROForm(data = request.POST,instance = mygrade)
if myform.is_valid():
grade = myform.save()
info =successfully updated%s%grade .studentId
else:
myform = GradeROForm(instance = mygrade)
return render_to_response('grade / modifyGrade.html',locals())
这显示了我期望的形式,但是当我点击提交时,我收到学生字段的表单验证错误,告诉我该字段是必需的。我猜测,由于该字段是禁用,所以该值不会在POST中报告,而且由于我不知道该实例未被使用的原因。
我是一个新的Django / Python程序员,但在其他语言方面颇有经验。我不敢相信我在第一个重要的django应用程序中偶然发现了这样一个难以解决的问题。我想我一定是缺少一些东西。任何想法?
您应该执行:
self.fields ['studentId']。widget.attrs ['readonly'] = True
,并确保不要覆盖回发的值。
此外,如果仍然存在必填字段的问题,您可以在模型中执行以下操作:
studentID = forms.CharField(label =A label,help_text =Student ID,required = False)
I'm writing a test "grade book" application. The models.py file is shown below.
class Student(models.Model):
name = models.CharField(max_length=50)
parent = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Grade(models.Model):
studentId = models.ForeignKey(Student)
finalGrade = models.CharField(max_length=3)
I'd like to be able to change the final grade for several students in a modelformset but for now I'm just trying one student at a time. I'm also trying to create a form for it that shows the student name as a field that can not be changed, the only thing that can be changed here is the finalGrade. So I used this trick to make the studentId read-only.
class GradeROForm(ModelForm):
studentId = forms.ModelChoiceField(queryset=Student.objects.all())
def __init__(self, *args, **kwargs):
super(GradeROForm,self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.id:
self.fields['studentId'].widget.attrs['disabled']='disabled'
def clean_studentId(self):
instance = getattr(self,'instance',None)
if instance:
return instance.studentId
else:
return self.cleaned_data.get('studentId',None)
class Meta:
model=Grade
And here is my view:
def modifyGrade(request,student):
student = Student.objects.get(name=student)
mygrade = Grade.objects.get(studentId=student)
if request.method == "POST":
myform = GradeROForm(data=request.POST, instance=mygrade)
if myform.is_valid():
grade = myform.save()
info = "successfully updated %s" % grade.studentId
else:
myform=GradeROForm(instance=mygrade)
return render_to_response('grades/modifyGrade.html',locals())
This displays the form like I expect, but when I hit "submit" I get a form validation error for the student field telling me this field is required. I'm guessing that, since the field is "disabled", the value is not being reported in the POST and for reasons unknown to me the instance isn't being used in its place.
I'm a new Django/Python programmer, but quite experienced in other languages. I can't believe I've stumbled upon such a difficult to solve problem in my first significant django app. I figure I must be missing something. Any ideas?
You should perform:
self.fields['studentId'].widget.attrs['readonly'] = True
and also make sure not to overwrite the value on postback.
Furthermore, if still having problems with the required field, you can do the following in your modelform:
studentID = forms.CharField(label="A label", help_text="Student ID", required=False)
这篇关于django中的强制性只读字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!