如何使用 url 参数(即用户 ID <str:pk>)预填充 DJANGO 表单中的字段
How can I use a url parameter(that is a user id <str:pk>) to prepopulate a field in DJANGO form
我正在做一个包含 2 个页面的管理应用程序:用户(客户)和一个包含用户付款历史记录(支票)的用户数据页面。
我正在尝试在付款历史页面 (cheques.html) 中创建一个表格来添加新的付款,但我希望 Cheque.cliente 等于当前用户 URL。例如:如果你的 URL 是 cheque/5/,那么 Cheque.cliente 应该是 5,当我添加一个新的付款时,付款应该被跟踪(ForeignKey)给用户 5(每个用户有很多付款)。
正在恢复:本应用有CRUD所有用户(客户)和所有付款(支票)的功能,但只有添加付款(支票)功能不起作用。
VIEWS.py
#CLIENTES
def index(request):
clientes = Cliente.objects.all()
form = ClienteForm()
if request.method == 'POST':
form = ClienteForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {'clientes':clientes, 'form':form}
return render(request, 'clientes/home.html', context)
#CHEQUES
#THE ERROR IS IN THIS VIEW!
def chequesCliente(request, pk):
cheques = Cheque.objects.filter(id=pk)
nome = Cliente.objects.get(id=pk)
formc = ChequeForm()
if request.method == 'POST':
formc = ChequeForm(request.POST)
print(formc.data['cliente'])
if formc.is_valid():
print(formc.cleaned_data)
formc.save()
return redirect('/')
context = {'cheques':cheques, 'formc':formc, 'nome':nome,}
return render(request, 'clientes/cheques.html', context)
def updateCheque(request, pk):
cheque = Cheque.objects.get(id=pk)
formc = ChequeForm(instance=cheque)
if request.method == 'POST':
formc = ChequeForm(request.POST, instance=cheque)
if formc.is_valid():
formc.save()
return redirect('/')
context = {'formc':formc}
return render(request, 'clientes/update_cheque.html', context)
def deleteCheque(request, pk):
item = Cheque.objects.get(id=pk)
if request.method == "POST":
item.delete()
return redirect('/')
context = {'item':item}
return render(request, 'clientes/delete_cheque.html', context)
URLS.py
path('admin/', admin.site.urls),
path('', views.index, name='lista'),
path('update/<str:pk>/', views.updateCliente, name="update"),
path('delete/<str:pk>/', views.deleteCliente, name="delete"),
path('cheques/<str:pk>/', views.chequesCliente, name="lista_cheques"),
#cliente/CRUD/num_cheque
path('update_cheque/<str:pk>/', views.updateCheque, name="update_cheque"),
path('delete_cheque/<str:pk>/', views.deleteCheque, name="delete_cheque"),
]
MODELS.py
nome = models.CharField(max_length=150)
cpf = models.CharField(max_length=14)
num = models.CharField(max_length=50)
endereco = models.CharField(max_length=150)
cidade = models.CharField(max_length=150)
limite = models.DecimalField(max_digits=9, decimal_places=2)
situacao = models.BooleanField(default=True)
def __str__(self):
return self.nome
class Cheque(models.Model):
cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE, related_name='cheques')
banco = models.CharField(max_length=25)
numero = models.IntegerField(default=0)
valor = models.DecimalField(max_digits=20, decimal_places=2)
emissao = models.DateField()
vencimento = models.DateField()
sem_fundos = models.BooleanField(default=False)
def __str__(self):
return self.banco
FORMS.py
class Meta:
model = Cliente
fields = '__all__'
class ChequeForm(forms.ModelForm):
class Meta:
model = Cheque
fields = '__all__'
exclude = ['cliente',]
TEMPLATES_cheques.HTML
<div id="flex_subheader">
<button type="button" class="my_btn" id="retornar" onclick="location.href='{% url 'clientes:lista' %}'"><span>Retornar</span></button>
<h2>{{ nome }}</h2></div>
<div id="adicionar_cheque" class="criar">
<form method="post" action=".">
{% csrf_token %}
{{ formc.non_field_errors }}
<table>
{{ formc.as_table }}
<input type="submit" id="sub_cheque" value="Confirmar!">
</table>
</form>
</div>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Banco</th>
<th scope="col">Número</th>
<th scope="col">Valor</th>
<th scope="col">Emissão</th>
<th scope="col">Vencimento</th>
<th scope="col">Sem Fundos</th>
</tr>
</thead>
<tbody>
{% for cheque in cheques %}
<tr>
<th scope="row">{{ cheque.pk }}</th>
<td>{{ cheque.banco }}</td>
<td>{{ cheque.numero }}</td>
<td>{{ cheque.valor }}</td>
<td>{{ cheque.emissao }}</td>
<td>{{ cheque.vencimento }}</td>
<td>{{ cheque.sem_fundos }}</td>
<td><a href="{% url 'clientes:update_cheque' cheque.id %}" class="my_btn" id="editar">Editar</a></td>
<td><a href="{% url 'clientes:delete_cheque' cheque.pk %}" class="my_btn" id="excluir">Excluir</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</section>
TEMPLATES_clientes.html
<tr>
<th scope="row">{{ cliente.pk }}</th>
<td> <a href="{% url 'clientes:lista_cheques' cliente.id %}"> {{ cliente.nome }} </a></td>
<td>{{ cliente.cpf }}</td>
<td>{{ cliente.num }}</td>
<td>{{ cliente.endereco }}</td>
<td>{{ cliente.cidade }}</td>
<td>{{ cliente.limite }}</td>
<td>{{ cliente.situacao }}</td>
<td><a href="{% url 'clientes:update' cliente.id %}" class="my_btn" id="editar">Editar</a></td>
<td><a href="{% url 'clientes:delete' cliente.id %}" class="my_btn" id="excluir">Excluir</a></td>
</tr>
{% endfor %}
保存表单时,可以添加参数commit=False。这将创建提交数据的对象,但不会将其保存在数据库中(不存在主键)。您可以在对象上更改数据,完成后保存对象:
if form.is_valid():
obj = form.save(commit=False) # returns an instance of a model object without pk
obj.field1 = some_value
obj.save() # Save the object to the db
我正在做一个包含 2 个页面的管理应用程序:用户(客户)和一个包含用户付款历史记录(支票)的用户数据页面。
我正在尝试在付款历史页面 (cheques.html) 中创建一个表格来添加新的付款,但我希望 Cheque.cliente 等于当前用户 URL。例如:如果你的 URL 是 cheque/5/,那么 Cheque.cliente 应该是 5,当我添加一个新的付款时,付款应该被跟踪(ForeignKey)给用户 5(每个用户有很多付款)。
正在恢复:本应用有CRUD所有用户(客户)和所有付款(支票)的功能,但只有添加付款(支票)功能不起作用。
VIEWS.py
#CLIENTES
def index(request):
clientes = Cliente.objects.all()
form = ClienteForm()
if request.method == 'POST':
form = ClienteForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {'clientes':clientes, 'form':form}
return render(request, 'clientes/home.html', context)
#CHEQUES
#THE ERROR IS IN THIS VIEW!
def chequesCliente(request, pk):
cheques = Cheque.objects.filter(id=pk)
nome = Cliente.objects.get(id=pk)
formc = ChequeForm()
if request.method == 'POST':
formc = ChequeForm(request.POST)
print(formc.data['cliente'])
if formc.is_valid():
print(formc.cleaned_data)
formc.save()
return redirect('/')
context = {'cheques':cheques, 'formc':formc, 'nome':nome,}
return render(request, 'clientes/cheques.html', context)
def updateCheque(request, pk):
cheque = Cheque.objects.get(id=pk)
formc = ChequeForm(instance=cheque)
if request.method == 'POST':
formc = ChequeForm(request.POST, instance=cheque)
if formc.is_valid():
formc.save()
return redirect('/')
context = {'formc':formc}
return render(request, 'clientes/update_cheque.html', context)
def deleteCheque(request, pk):
item = Cheque.objects.get(id=pk)
if request.method == "POST":
item.delete()
return redirect('/')
context = {'item':item}
return render(request, 'clientes/delete_cheque.html', context)
URLS.py
path('admin/', admin.site.urls),
path('', views.index, name='lista'),
path('update/<str:pk>/', views.updateCliente, name="update"),
path('delete/<str:pk>/', views.deleteCliente, name="delete"),
path('cheques/<str:pk>/', views.chequesCliente, name="lista_cheques"),
#cliente/CRUD/num_cheque
path('update_cheque/<str:pk>/', views.updateCheque, name="update_cheque"),
path('delete_cheque/<str:pk>/', views.deleteCheque, name="delete_cheque"),
]
MODELS.py
nome = models.CharField(max_length=150)
cpf = models.CharField(max_length=14)
num = models.CharField(max_length=50)
endereco = models.CharField(max_length=150)
cidade = models.CharField(max_length=150)
limite = models.DecimalField(max_digits=9, decimal_places=2)
situacao = models.BooleanField(default=True)
def __str__(self):
return self.nome
class Cheque(models.Model):
cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE, related_name='cheques')
banco = models.CharField(max_length=25)
numero = models.IntegerField(default=0)
valor = models.DecimalField(max_digits=20, decimal_places=2)
emissao = models.DateField()
vencimento = models.DateField()
sem_fundos = models.BooleanField(default=False)
def __str__(self):
return self.banco
FORMS.py
class Meta:
model = Cliente
fields = '__all__'
class ChequeForm(forms.ModelForm):
class Meta:
model = Cheque
fields = '__all__'
exclude = ['cliente',]
TEMPLATES_cheques.HTML
<div id="flex_subheader">
<button type="button" class="my_btn" id="retornar" onclick="location.href='{% url 'clientes:lista' %}'"><span>Retornar</span></button>
<h2>{{ nome }}</h2></div>
<div id="adicionar_cheque" class="criar">
<form method="post" action=".">
{% csrf_token %}
{{ formc.non_field_errors }}
<table>
{{ formc.as_table }}
<input type="submit" id="sub_cheque" value="Confirmar!">
</table>
</form>
</div>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Banco</th>
<th scope="col">Número</th>
<th scope="col">Valor</th>
<th scope="col">Emissão</th>
<th scope="col">Vencimento</th>
<th scope="col">Sem Fundos</th>
</tr>
</thead>
<tbody>
{% for cheque in cheques %}
<tr>
<th scope="row">{{ cheque.pk }}</th>
<td>{{ cheque.banco }}</td>
<td>{{ cheque.numero }}</td>
<td>{{ cheque.valor }}</td>
<td>{{ cheque.emissao }}</td>
<td>{{ cheque.vencimento }}</td>
<td>{{ cheque.sem_fundos }}</td>
<td><a href="{% url 'clientes:update_cheque' cheque.id %}" class="my_btn" id="editar">Editar</a></td>
<td><a href="{% url 'clientes:delete_cheque' cheque.pk %}" class="my_btn" id="excluir">Excluir</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</section>
TEMPLATES_clientes.html
<tr>
<th scope="row">{{ cliente.pk }}</th>
<td> <a href="{% url 'clientes:lista_cheques' cliente.id %}"> {{ cliente.nome }} </a></td>
<td>{{ cliente.cpf }}</td>
<td>{{ cliente.num }}</td>
<td>{{ cliente.endereco }}</td>
<td>{{ cliente.cidade }}</td>
<td>{{ cliente.limite }}</td>
<td>{{ cliente.situacao }}</td>
<td><a href="{% url 'clientes:update' cliente.id %}" class="my_btn" id="editar">Editar</a></td>
<td><a href="{% url 'clientes:delete' cliente.id %}" class="my_btn" id="excluir">Excluir</a></td>
</tr>
{% endfor %}
保存表单时,可以添加参数commit=False。这将创建提交数据的对象,但不会将其保存在数据库中(不存在主键)。您可以在对象上更改数据,完成后保存对象:
if form.is_valid():
obj = form.save(commit=False) # returns an instance of a model object without pk
obj.field1 = some_value
obj.save() # Save the object to the db