从HTML中使用Zip_longest()函数数据获取Django模型的ID

huangapple go评论64阅读模式
英文:

Django get Models ID from Zip_longest() function data on HTML

问题

我正在开发一个Django应用程序,在其中我使用了Python的zip_longest函数以及for循环来在HTML表格中显示客户存款和取款记录,我想要将第二个zipped列表项目的ID传递到按钮的URL中。我该如何实现这一目标。

这是我的模型(Model)部分:

class Witdrawal(models.Model):
    account = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
    transID = models.CharField(max_length=12, null=True)
    staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    withdrawal_amount = models.PositiveIntegerField(null=True)
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f'{self.account}- Withdrawn - {self.withdrawal_amount}'

这是我的第一个视图(View)部分:

@login_required(login_url='user-login')
def account_statement(request, id):
    try:
        customer = Account.objects.get(id=id)
        # 获取客户ID
        customerID = customer.customer.id
    except Account.DoesNotExist:
        messages.error(request, 'Something Went Wrong')
        return redirect('create-customer')
    else:
        deposits = Deposit.objects.filter(customer__id=customerID).order_by('-date')[:5]
        # 获取客户取款记录通过ID,并按日期倒序显示最多5条记录
        withdrawals = Witdrawal.objects.filter(account__id=customerID).order_by('-date')[:5]
    context = {
        "deposits_and_withdrawals": zip_longest(deposits, withdrawals, fillvalue='No Transaction'),
    }
    return render(request, 'dashboard/statement.html', context)

这是我的HTML代码部分:

{% if deposits_and_withdrawals %}
    <tbody>
        {% for deposit, withdrawal in deposits_and_withdrawals %}
        <tr>
            <td style="background-color:rgba(231, 232, 233, 0.919); color:blue;">Deposit - </td>
            <td style="background-color:rgba(231, 232, 233, 0.919)">{{ deposit.acct }}</td>
            <td style="background-color:rgba(231, 232, 233, 0.919)">{{ deposit.transID }}</td>
            <td style="background-color:rgba(231, 232, 233, 0.919)">N{{ deposit.deposit_amount | intcomma }}</td>
            <td style="background-color:rgba(231, 232, 233, 0.919)">{{ deposit.date | naturaltime }}</td>
            <th scope="row" style="background-color:rgba(231, 232, 233, 0.919)">
                <a class="btn btn-success btn-sm" href="{% url 'deposit-slip' deposit.id %}">Slip</a>
            </th>
        </tr>
        <tr style="color: red;">
            <td>Withdrawal - </td>
            <td>{{ withdrawal.account.surname }}</td>
            <td>{{ withdrawal.transID }}</td>
            <td>N{{ withdrawal.withdrawal_amount | intcomma }}</td>
            <td>{{ withdrawal.date | naturaltime }}</td>
            <th scope="row">
                <a class="btn btn-success btn-sm" href="{% url 'withdrawal-slip' withdrawal.id %}">Slip</a>
            </th>
        </tr>
        {% endfor %}
    </tbody>
{% else %}
    <h3 style="text-align: center; color:red;">No Deposit/Withdrawal Found for {{ customer.customer.profile.surname }} {{ customer.customer.profile.othernames }}</h3>
{% endif %}

这是我的URL路径部分:

urlpatterns = [
    path('withdrawal/slip/<int:id>/', user_view.withdrawal_slip, name='withdrawal-slip'),
]

请理解我试图在withdrawal_slip函数的URL路径中获取withdrawal id,但是我得到了这个错误:NoReverseMatch at /account/1/statement/ Reverse for 'withdrawal-slip' with arguments '()', not found. 1 pattern(s) tried: ['withdrawal/slip/(?P[0-9]+)/\Z']。错误指向了我的HTML中按钮的URL代码行,但我不知道问题出在哪里。

英文:

I am working a Django application where I have used python zip_longest function with a the for loop for displaying both the Customer Deposits and Withdrawals in an HTML Table, and I want to get the second zipped list item ID unto a url in a button. How do I achieve this.
Here is my Model:

class Witdrawal(models.Model): 
    account = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
    transID = models.CharField(max_length=12, null=True)
    staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    withdrawal_amount = models.PositiveIntegerField(null=True)
    date = models.DateTimeField(auto_now_add=True)


    def __str__(self):
        return f&#39;{self.account}- Withdrawn - {self.withdrawal_amount}&#39;

Here is my first view:

@login_required(login_url=&#39;user-login&#39;)

def account_statement(request, id):

    try:
       customer = Account.objects.get(id=id)
       #Get Customer ID
       customerID = customer.customer.id
        
    except Account.DoesNotExist:
        messages.error(request, &#39;Something Went Wrong&#39;)
        return redirect(&#39;create-customer&#39;)
    else:
        deposits = Deposit.objects.filter(customer__id=customerID).order_by(&#39;-date&#39;)[:5]
        #Get Customer Withdrawal by ID and order by Date minimum 5 records displayed
        withdrawals = Witdrawal.objects.filter(account__id=customerID).order_by(&#39;-date&#39;)[:5]
   context = {
    &quot;deposits_and_withdrawals&quot;: zip_longest(deposits, withdrawals, fillvalue=&#39;No Transaction&#39;),
   }
   return render(request, &#39;dashboard/statement.html&#39;, context)

Here is my HTML code:

{% if deposits_and_withdrawals %}
                    &lt;tbody&gt;
                    
                      
                      {% for deposit, withdrawal in deposits_and_withdrawals %}  
                      &lt;tr&gt;
                        &lt;td style=&quot;background-color:rgba(231, 232, 233, 0.919); color:blue;&quot;&gt;Deposit - &lt;/td&gt;
                        &lt;td style=&quot;background-color:rgba(231, 232, 233, 0.919)&quot;&gt;{{ deposit.acct }}&lt;/td&gt;
                        &lt;td style=&quot;background-color:rgba(231, 232, 233, 0.919)&quot;&gt;{{ deposit.transID }}&lt;/td&gt; 
                        &lt;td style=&quot;background-color:rgba(231, 232, 233, 0.919)&quot;&gt;N{{ deposit.deposit_amount | intcomma }}&lt;/td&gt;
                        &lt;td style=&quot;background-color:rgba(231, 232, 233, 0.919)&quot;&gt;{{ deposit.date | naturaltime }}&lt;/td&gt;
                        
                        &lt;th scope=&quot;row&quot; style=&quot;background-color:rgba(231, 232, 233, 0.919)&quot;&gt;&lt;a class=&quot;btn btn-success btn-sm&quot; href=&quot;{% url &#39;deposit-slip&#39; deposit.id %}&quot;&gt;Slip&lt;/a&gt;&lt;/th&gt;
                      &lt;/tr&gt;

                      &lt;tr style=&quot;color: red;&quot;&gt;
                        &lt;td&gt;Withdrawal - &lt;/td&gt;
                        &lt;td&gt;{{ withdrawal.account.surname }}&lt;/td&gt;
                        &lt;td&gt;{{ withdrawal.transID }}&lt;/td&gt; 
                        &lt;td&gt;N{{ withdrawal.withdrawal_amount | intcomma }}&lt;/td&gt;
                        &lt;td&gt;{{ withdrawal.date | naturaltime }}&lt;/td&gt;
                        
                        &lt;th scope=&quot;row&quot;&gt;&lt;a class=&quot;btn btn-success btn-sm&quot; href=&quot; {% url &#39;withdrawal-slip&#39; withdrawal.withdrawal_id %} &quot;&gt;Slip&lt;/a&gt;&lt;/th&gt;
                      &lt;/tr&gt;
                      {% endfor %}  
                                 
                    &lt;/tbody&gt;
                    {% else %}
                    &lt;h3 style=&quot;text-align: center; color:red;&quot;&gt;No Deposit/Withdrawal Found for {{ customer.customer.profile.surname }} {{ customer.customer.profile.othernames }}&lt;/h3&gt;
                    {% endif %}

Here is my URL path code:

urlpatterns = [
path(&#39;witdrawal/slip/&lt;int:id&gt;/&#39;, user_view.withdrawal_slip, name = &#39;withdrawal-slip&#39;),
]

Please, understand I am trying to get the withdrawal id for the withdrawal_slip function URL Path but this is the error I am getting NoReverseMatch at /account/1/statement/
Reverse for 'withdrawal-slip' with arguments '('',)' not found. 1 pattern(s) tried: ['witdrawal/slip/(?P<id>[0-9]+)/\Z']
. The error is pointing to the Button's URL code number in my HTML but I don't know what is the issue.

答案1

得分: 0

应该使用withdrawal.id而不是withdrawal.withdrawal_id,像这样:

{% url 'withdrawal-slip' withdrawal.id %}

或者,如果您发送的是transID,也可以使用transID,如下:

{% url 'withdrawal-slip' withdrawal.transID %}

所以请记得将<int:id>更改为<str:trans_id>,因为它是CharField,如下:

path('withdrawal/slip/<str:trans_id>/', user_view.withdrawal_slip, name='withdrawal-slip')
英文:

It should be withdrawal.id instead of withdrawal.withdrawal_id, like so:

{% url &#39;withdrawal-slip&#39; withdrawal.id %}

Or maybe you want transID if you send transID as:

{% url &#39;withdrawal-slip&#39; withdrawal.transID %}

So remeber to change &lt;int:id&gt; to &lt;str:trans_id&gt; since it is CharField, like so:

path(&#39;withdrawal/slip/&lt;str:trans_id&gt;/&#39;, user_view.withdrawal_slip, name=&#39;withdrawal-slip&#39;)

huangapple
  • 本文由 发表于 2023年3月4日 09:22:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75633108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定