Mandatory read-only fields in django

I am writing a classroom test 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 would like to be able to change the final class for several students in the model set, but for now, I'm just trying one student at a time. I am also trying to create a form for him that shows the student’s name as a field that cannot be changed, the only thing that can be changed here is finalGrade. So I used this trick to make 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 opinion:

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())

, , "submit", , , . , , "", POST .

Django/Python, . , ​​ django. , - . ?

+3
1

:

self.fields['studentId'].widget.attrs['readonly'] = True

.

, , :

studentID = forms.CharField(label="A label", help_text="Student ID", required=False)
+6

Source: https://habr.com/ru/post/1747634/


All Articles