CharField values disappearing after save (readonly field)

Posted by jamida on Stack Overflow See other posts from Stack Overflow or by jamida
Published on 2010-05-31T17:42:17Z Indexed on 2010/05/31 17:43 UTC
Read the original article Hit count: 409

I'm implementing simple "grade book" application where the teacher would be able to update the grades w/o being allowed to change the students' names (at least not on the update grade page). To do this I'm using one of the read-only tricks, the simplest one. The problem is that after the SUBMIT the view is re-displayed with 'blank' values for the students. I'd like the students' names to re-appear.

Below is the simplest example that exhibits this problem. (This is poor DB design, I know, I've extracted just the relevant parts of the code to showcase the problem. In the real example, student is in its own table but the problem still exists there.)

models.py

class Grade1(models.Model):
    student = models.CharField(max_length=50, unique=True)
    finalGrade = models.CharField(max_length=3)

class Grade1OForm(ModelForm):
    student = forms.CharField(max_length=50, required=False)
    def __init__(self, *args, **kwargs):
        super(Grade1OForm,self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.id:
            self.fields['student'].widget.attrs['readonly'] = True
            self.fields['student'].widget.attrs['disabled'] = 'disabled'
    def clean_student(self):
        instance = getattr(self,'instance',None)
        if instance:
            return instance.student
        else:
            return self.cleaned_data.get('student',None)
    class Meta:
        model=Grade1

views.py

from django.forms.models import modelformset_factory
def modifyAllGrades1(request):
    gradeFormSetFactory = modelformset_factory(Grade1, form=Grade1OForm, extra=0)
    studentQueryset = Grade1.objects.all()
    if request.method=='POST':
        myGradeFormSet = gradeFormSetFactory(request.POST, queryset=studentQueryset)
        if myGradeFormSet.is_valid():
            myGradeFormSet.save()
            info = "successfully modified"
    else:
        myGradeFormSet = gradeFormSetFactory(queryset=studentQueryset)
    return render_to_response('grades/modifyAllGrades.html',locals())

template

<p>{{ info }}</p>
<form method="POST" action="">
<table>
{{ myGradeFormSet.management_form }}
{% for myform in myGradeFormSet.forms %}
  {# myform.as_table #}
  <tr>
    {% for field in myform %}
    <td> {{ field }} {{ field.errors }} </td>
    {% endfor %}
  </tr>
{% endfor %}
</table>
<input type="submit" value="Submit">
</form>

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models