I am having a problem with a test application that I am writing to test the functionality of Django. The test application is a small classroom application that currently uses Alex Gaynor flight functionality to read only http://lazypython.blogspot.com/2008/12/building-read-only-field-in- django.html
There are two problems that may be related. First, when I overlay a comment on these two lines below:
it works as I expect, except that the student field is volatile.
When comments are displayed in this order, the "studentId" field is displayed as a number (not a name, problem 1), and when I click submit, I get an error saying that studentId must be an instance of Student.
I don’t understand how to fix this. I am not tied to Alex Gaynor code. Any code will work. I'm relatively new to both Python and Django, so the tips I saw on websites that say “make the read-only field easy” still don't fit me.
//models.py
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)
//views.py
def modifyGrade(request,student): student = Student.objects.get(name=student) mygrade = Grade.objects.get(studentId=student) if request.method == "POST": # myform = GradeForm(data=request.POST, instance=mygrade) myform = GradeROForm(data=request.POST, instance=mygrade) if myform.is_valid(): grade = myform.save() info = "successfully updated %s" % grade.studentId else: # myform=GradeForm(instance=mygrade) myform=GradeROForm(instance=mygrade) return render_to_response('grades/modifyGrade.html',locals())
//template
<p>{{ info }}</p> <form method="POST" action=""> <table> {{ myform.as_table }} </table> <input type="submit" value="Submit"> </form>
// Code Alex Gaynor
from django import forms from django.utils.html import escape from django.utils.safestring import mark_safe from django.forms.util import flatatt class ReadOnlyWidget(forms.Widget): def render(self, name, value, attrs): final_attrs = self.build_attrs(attrs, name=name) if hasattr(self, 'initial'): value = self.initial return mark_safe("<span %s>%s</span>" % (flatatt(final_attrs), escape(value) or '')) def _has_changed(self, initial, data): return False class ReadOnlyField(forms.FileField): widget = ReadOnlyWidget def __init__(self, widget=None, label=None, initial=None, help_text=None): forms.Field.__init__(self, label=label, initial=initial, help_text=help_text, widget=widget) def clean(self, value, initial): self.widget.initial = initial return initial