我创建了两个类:客户端(属性:名称和性别)和帐户(属性:客户[fk],付款状态)。我从模板中显示表单;当我点击“添加客户”链接时,它会打开创建的形式,从models.py中的内容,其他单词只能创建一个“名称和性别”的客户端,但不是我可以集成在相同的表单付款情况。
models.py
from django.db import models
class Cliente(models.Model):
SEXO = (
('M', 'Masculino'),
('F','Feminino'),
)
nome = models.CharField("Nome do cliente", max_length=255)
sexo = models.CharField("Sexo", max_length=1, choices=SEXO)
def __unicode__(self):
return self.nome
class Meta:
verbose_name = 'Cliente'
verbose_name_plural = 'Clientes'
class Conta(models.Model):
STATUS_CONTA = (
('A', 'A Pagar'),
('P', 'Pago'),
)
cliente = models.ForeignKey(Cliente, related_name='conta')
situacao = models.CharField("Situação", max_length=50, choices=STATUS_CONTA)
class Meta:
verbose_name = 'Conta'
verbose_name_plural = 'Contas'
def __unicode__(self):
return self.cliente.nome
forms.py
from django.forms.models import ModelForm
from cadastro.models import Cliente, Conta
__author__ = 'Admin'
class ClienteForm(ModelForm):
class Meta:
model = Cliente
的index.html
<html>
<body>
<a href='/adicionar_cliente/'>Adicionar cliente</a>
{% for cliente in clientes %}
{% for conta in cliente.conta.all %}
<p>Nome: {{cliente.nome}}</p>
<p>Sexo: {{cliente.get_sexo_display}} </p>
<p>Situação do pedido: {{conta.get_situacao_display}}</p>
{% endfor %}
<p><a href='/excluir/{{cliente.id}}/'>Excluir?</a></p>
<p><a href='/editar/{{cliente.id}}/'>Editar</a></p>
<hr>
{% empty %}
<h3>Não existe nenhum cliente.</h3>
{% endfor %}
</body>
</html>
form.html
<html>
<body>
<form action='/{{action}}/' method='post'>
{% csrf_token %}
<table>
{{form}}
</table>
<input type='submit' value='Adicionar' />
</form>
</body>
</html>
答案 0 :(得分:2)
您可以创建两个表单来完成此任务。
...
class ClienteForm(ModelForm):
class Meta:
model = Cliente
class ContaForm(ModelForm):
class Meta:
model = Conta
exclude = ("cliente") #exclude the cliente field from showing up in the form rendering.
<html>
<body>
<form action='/{{ action }}/' method='post'>
{% csrf_token %}
<table>
{{ form.as_table }} <!-- added as table which was missing from original post. -->
{{ form2.as_table }}
</table>
<input type='submit' value='Adicionar' />
</form>
</body>
...
def form(request):
if request.method == 'POST':
form = ClienteForm(request.POST)
form2 = ContaForm(request.POST)
if form.is_valid() and form2.is_valid():
client = form.save()
conta = form2.save(commit=False)
conta.cliente = client
contra.save()
else:
form = ClienteForm()
form2 = ContaForm()
return render_to_response('form.html', locals(), context_instance = RequestContext(request))