我在這裏遇到問題,我希望你能幫助我。Django - 沒有正確顯示模板中的一張表
這裏就是我有:
Models.py
class Personinfo(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Personage(models.Model):
AGES = (
('0', '0'),
('1', '1'),
('2', '2'),
)
age = models.CharField(max_length=128,choices=AGES, default=True)
def __str__(self):
return self.age
class Person(models.Model):
person = models.ForeignKey(Personinfo, null=True)
personage = models.ForeignKey(Personage, null=True)
address = models.TextField()
phone_number = models.CharField(max_length=128)
hobbies =models.CharField(max_length=128)
def __str__(self):
return self.address
Views.py
def index(request):
qs = Person.objects.all()
form = personform(request.POST or None)
form2 = personinfoform(request.POST or None)
form3 = personageform(request.POST or None)
context = {
"qs": qs,
"form2":form2,
"form":form,
"form3":form3,
}
form2_valid = form2.is_valid()
form_valid = form.is_valid()
form3_valid = form3.is_valid()
if form2_valid and form_valid and form3_valid:
a = form2.save()
b= form.save(commit=False)
b.person = a
b.save()
c = form3.save(commit=False)
c.personage = a
c.save()
return render(request, "index.html", context)
forms.py
class personinfoform(forms.ModelForm):
name = forms.CharField(label= 'Nombre')
class Meta:
model = Personinfo
fields = ["name"]
class personform(forms.ModelForm):
address = forms.CharField(label='Direccion')
phone_number = forms.CharField(label='Telefono')
hobbies = forms.CharField(label='Hobbies')
class Meta:
model = Person
exclude = ('person','personage',)
fields = ["address","phone_number","hobbies"]
class personageform(forms.ModelForm):
class Meta:
model = Personage
fields =["age"]
的index.html
<form method="POST" action="">{% csrf_token %}
{{form2.as_p}}
{{form3.as_p}}
{{form.as_p}}
<input type="submit" value="Save!" />
</form>
<table >
<tr>
<th>Name</th>
<th>Age</th>
<th>Address</th>
<th>Telefono</th>
<th>Hobbies</th>
</tr>
{% for p in qs %}
<tr>
<td>{{ p.person.name}}</td>
<td>{{ p.personage.age }}</td>
<td>{{ p.address }}</td>
<td>{{ p.phone_number }}</td>
<td>{{ p.hobbies }}</td>
</tr>
{% endfor %}
</table>
正如你可以看到我有3種形式,它的保存正確,但它不是我的person.name
模板被顯示,我想personage.age
我想使其完全如Personinfo
,但它不工作。怎麼了?
基本上我想Personage
工作exacly爲Personinfo
。
謝謝..!
你檢查數據庫的'Personinfo價值表?代碼看起來很好。 –