hi
I am learning the use of Forms and tried populating a form from an
instance.Here I encountered a problem.
I have a class Lecture which can belong to diff subjects.So I created
a field 'subjects' in Lecture to be a ManyToManyField.
For example,
Lecture1 -data structures,algorithms
Lecture2 -data structures,c programming
Lecture3 -algorithms,java
I created ModelForms for Lecture and Subject .Then I created another
SubjectNamesForm( which has no associated Model )to capture the many
subject names a Lecture can have.
When I edit a Lecture, I need to show the existing values from the
Lecture in the template,so I used
<form method='POST' action="{%url edit_lecture
lectureform.instance.id %}>
<table>
{{lectureform.as_table }}
</table>
<table>
{{subjectnamesform.as_table }}
</table>
<input type="submit" value="Submit">
</form>
I can populate the LectureForm with info from existing instance
using
lecture=get_object_or_404(Lecture,id)
lectureform=LectureForm(request.POST,instance=lecture)
But how do I populate the subjectnamesform ? I tried the
following ,but it shows only empty text field when subjectnamesform is
rendered
if request.method=='GET':
....
subjectnamesform=SubjectNamesForm()
subjectnamesform.subjects=[x.name for x in lecture.subjects.all()]
return render_to_response('myapp/edit_lecture.html',
{'lectureform':lectureform,'subjectnamesform':subjectnamesform})
Can someone help?
thanks
harry
p.s:
below is the listing of models.
class Lecture(models.Model):
speaker=models.ForeignKey(User)
subjects=models.ManyToManyField(Subject)
pub_date=models.DateField(default=date.today)
class Subject(models.Model):
name=models.CharField(unique=True,max_length=50)
class LectureForm(forms.ModelForm):
class Meta:
model=Lecture
exclude=('subjects',)
class SubjectForm(forms.ModelForm):
class Meta:
model=Subject
class SubjectNamesForm(forms.Form):
subjects=models.CharField(max_length=400)# expects comma separated
subject names like subject1,subject2 etc
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.