簡體   English   中英

如何使用 url 參數(即用戶 ID<str:pk> ) 以 DJANGO 形式預填充字段</str:pk>

[英]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 的功能,但只有添加付款(支票)function 不起作用。

視圖.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"),
] 

模型.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。 這將創建提交數據的對象,但不會將其保存在數據庫中(不存在主鍵)。 在 object 上,您可以更改數據,完成后,保存 object:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM