简体   繁体   English

确认后如何提交 Django 表格

[英]How can I Submit Django Form after Confirmation

I am working on a Saving App where I want user to add Customer Deposits after displaying a confirmation form with message.我正在开发一个储蓄应用程序,我希望用户在显示带有消息的确认表单后添加客户存款。 I have tried all I could but I realised that the Deposit function is working fine and displaying the confirmation message but on click confirm on the confirmation form it is not able to submit the deposit form, rather the system redirects me back to deposit form again;我已尽我所能,但我意识到存款 function 工作正常并显示确认消息,但在确认表单上单击确认时无法提交存款表单,而是系统将我再次重定向回存款表单; displaying an error on the input form that amount Field Can Not be Empty.在输入表单上显示金额字段不能为空的错误。

Model Code: Model 代码:

class Deposit(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True)
    acct = models.CharField(max_length=6, null=True)
    staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    deposit_amount = models.PositiveIntegerField(null=True)
    date = models.DateTimeField(auto_now_add=True)

    def get_absolute_url(self):
        return reverse('create_account', args=[self.id])

    def __str__(self):
       return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}'

Form Code:表格代码:

class CustomerDepositForm(forms.ModelForm):

    class Meta:
       model = Deposit
       fields = ['deposit_amount']

Views Code:查看代码:

def customer_deposit(request, id):
    context = {}
    form = CustomerDepositForm(request.POST or None)
    #Set Page Title
    page_title = "Customer Deposit"
    #Get Current Date
    current_date = datetime.now().date()
    #Get Current Month Name from Calendar
    current_month_name = calendar.month_name[date.today().month]

    try:
        #Check the Customer ID in DB
        customer = Customer.objects.get(id=id)
        #Customer Account
        acct = customer.account_number
   except Customer.DoesNotExist:
        messages.error(request, 'Customer Does Not Exist')
        return redirect('customer_create')
   else:
       #Get the Customer total deposit
       deposit = Deposit.objects.filter(customer_id = id).aggregate(total=Sum('deposit_amount')
       )['total'] or Decimal()
       if request.method == 'POST':
            #Deposit Form
            form = CustomerDepositForm(request.POST or None)
            if form.is_valid():
                amount = form.cleaned_data['deposit_amount']
                context.update(  {
                'deposit':deposit,
                'page_title':page_title,
                'customer':customer,
                'current_date':current_date,
                'current_month_name':current_month_name,
                'form':form,
                'amount':amount,
                'acct':acct,
                })
                return render(request, 'dashboard/deposit_approval_form.html', context)
            
        else:
            form = CustomerDepositForm()
            context = {
            'deposit':deposit,
            'page_title':page_title,
            'customer':customer,
            'current_date':current_date,
            'current_month_name':current_month_name,
            'form':form,
        
            'acct':acct,
            }
            return render(request, 'dashboard/deposit.html', context)

def approve_deposit(request, id):
    user = request.user
    form = CustomerDepositForm(request.POST or None)
    amount = form.cleaned_data['deposit_amount'].value()
    try:
        #Check the Customer ID in DB
        customer = Customer.objects.get(id=id)
        #Customer Account
        acct = customer.account_number
   except Customer.DoesNotExist:
       messages.error(request, 'Customer Does Not Exist')
       return redirect('customer_create')
   else:
       if request.method == 'POST':
           #Create Customer Deposit
           credit_acct = Deposit.objects.create(customer=customer, acct=acct, staff=user,    deposit_amount=amount)
           credit_acct.save()
           messages.success(request, f'N{amount} Credited for Account {acct} Successfully.')
           return redirect('deposit-slip')
               
      else:
          form = CustomerDepositForm()

return render(request, 'dashboard/deposit_approval_form.html')

Deposit Approval Template code:存款批准模板代码:

<form method="POST">
               {% csrf_token %} 

             

            <a class="btn btn-secondary" href="{% url 'create-deposit' customer.id %}">Cancel</a>

               <input class="btn btn-danger" type="submit" value="Confirm">
           </form>

Someone should help with the best way of achieving this.有人应该帮助实现这一目标的最佳方式。 Thanks谢谢

You have to use null=True, blank=True For field which you are not using in form.您必须使用null=True, blank=True对于您未在表单中使用的字段。 And then make migrations again然后再次进行迁移

null = True, blank = False means that field can be empty in DATABASE but NOT IN FORM and vice versa. null = True, blank = False表示该字段在 DATABASE 中可以为空,但不能在 FORM 中,反之亦然。

From my Observation, you're not submitting the form in the try block , you are only submitting the form in the else block .根据我的观察,您没有在try block中提交表单,您只是在else block中提交表单。 The form will never submit because the try block is always true表单永远不会提交,因为try block始终为 true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM