【问题标题】:Django Error NoReverseMatch at /invest/(?P1\d+)//invest/(?P1\d+)/ 处的 Django 错误 NoReverseMatch
【发布时间】:2021-06-18 22:15:54
【问题描述】:
  • 所以我正在尝试更新 django 中的值。但是当点击提交时,它会抛出一个错误。
NoReverseMatch at /invest/(?P1\d+)/
Reverse for 'invest' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['invest/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)/$']
Request Method: POST
Request URL:    http://127.0.0.1:8000/invest/(%3FP1%5Cd+)/
Django Version: 3.1.7
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'invest' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['invest/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)/$']
Exception Location: C:\Users\Harsh-PC\AppData\Roaming\Python\Python37\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix
Python Executable:  C:\Program Files\Python37\python.exe
Python Version: 3.7.9
Python Path:    
['E:\\Colosseum 2021\\django_colo',
 'C:\\Program Files\\Python37\\python37.zip',
 'C:\\Program Files\\Python37\\DLLs',
 'C:\\Program Files\\Python37\\lib',
 'C:\\Program Files\\Python37',
 'C:\\Users\\Harsh-PC\\AppData\\Roaming\\Python\\Python37\\site-packages',
 'C:\\Users\\Harsh-PC\\AppData\\Roaming\\Python\\Python37\\site-packages\\win32',
 'C:\\Users\\Harsh-PC\\AppData\\Roaming\\Python\\Python37\\site-packages\\win32\\lib',
 'C:\\Users\\Harsh-PC\\AppData\\Roaming\\Python\\Python37\\site-packages\\Pythonwin',
 'C:\\Program Files\\Python37\\lib\\site-packages']
Server time:    Mon, 22 Mar 2021 09:21:50 +0000
  • 我以这种方式从brand.html页面调用invest页面
        <a href="{% url 'invest' pk=marking.id %}";><button type="button" class="btn btn-primary" data-toggle="modal" >Invest</button></a>

  • 我在 html 代码中正确传递了值
<script>
                $(document).on('submit', '#post-form',function(e){
                    // console.log("Amount="+$('input[name="amount"]').val());
                    e.preventDefault();
                    // getting the value entered
                    amount = $('input[name="amount"]').val();
                    product_title = $('input[name="product_title"]').val();
                    console.log("Product title="+product_title);
                    console.log("Amount entered by user="+amount);
                    $.ajax({
                        type:'POST',
                        url:"{% url 'invest' pk=context.id %}",
                        data:{
                            product_title: product_title,
                            amount: amount,
                            csrfmiddlewaretoken: '{{ csrf_token }}',
                            action: 'post'
                        },
                        success: function(xhr, errmsg, err){
                          window.location = "brand"
                        },
                        error : function(xhr,errmsg,err) {
                        $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                            " <a href='#' class='close'>&times;</a></div>");
                        console.log(xhr.status + ": " + xhr.responseText); 
                    }
                    });
                });
              </script>
  • urls.py
path('invest/(?P<pk>\d+)/', views.invest, name='invest'),
  • views.py
def invest(request, pk):
    # fetching the current event details
    event_data = MarketingMaestro.objects.get(pk = pk)
    context = {
            'id' : event_data.id,
            'product_title' : event_data.product_title,
            'total_value' : event_data.total_value,
            'total_votes' : event_data.total_votes,
            }

    # fetching user details
    user_data = MarketingInvesment.objects.get(emailID = request.user.email)
    user_details = {
        'name' : user_data.name,
        'emailID' : user_data.emailID,
        'remaining_amount' : user_data.remaining_amount
    }

    total_value_db = event_data.total_value 

    # updating the user amount
    # try:
        # checking if the user exist in UserProfile through the logged in email id
    if request.POST.get('action') == 'post':
        response_data = {}
        name = request.user.username
        emailID = request.user.email
        # remaining amount from db
        remaining_amount = user_data.remaining_amount
        product_title = request.POST.get('product_title')
        # getting user amount
        user_amount = request.POST.get('amount')
        user_amount_final = int(user_amount)

        user_amount_db = total_value_db + user_amount_final
        final_amount = remaining_amount - user_amount_final

        response_data['name'] = name
        response_data['emailID'] = emailID
        response_data['remaining_amount'] = remaining_amount
        response_data['product_title'] = product_title
            # updating the current logged in user values
        user_data = MarketingInvesment.objects.get(emailID = request.user.email)
        if(user_data.emailID == request.user.email):
            MarketingInvesment.objects.filter(emailID = request.user.email).update(
                name = name,
                emailID = emailID,
                remaining_amount = final_amount,
                product_title = product_title,
                total_investment = user_amount_db
            )
        return render(request, 'invest.html')
    return render(request, 'invest.html', {'context' : context, 'user_details' : user_details})

【问题讨论】:

  • 只是一个想法 - 我是否需要再创建一个方法,因为我再次调用相同的方法,是否会导致问题?
  • 你能分享完整的错误跟踪吗
  • @c.grey 我已经更新,现在你可以检查了
  • 什么是 context.id ?????在你的 Ajax 中
  • 您从哪里获得marking.id?这是您在 url 语句中指定的参数,但此参数未在请求视图中提交。

标签: python django ajax


【解决方案1】:

我认为在使用 URL 正则表达式时应该使用 url,因为路径不支持正则表达式,这里是 docs for path()。您可以像这样在 url 中使用正则表达式:

from django.conf.urls import url

url(r'^invest/(?P<pk>[\w-]+)/', views.invest, name='invest'),
...

我认为您没有在上下文中添加标记对象

【讨论】:

  • 这并不能解决我的错误。我仍然面临错误。
  • 我在您的代码中看到的另一件事,您是否在上下文中添加了标记对象?
  • 是的,我正在从数据库中检索并将其传递给invest.html
  • 您是如何从数据库中检索它而不将其呈现到上下文字典中的?
  • 你可以检查投资方法,我已经检索然后渲染,在最后一行我也通过了它return render(request, 'invest.html', {'context' : context, 'user_details' : user_details})
【解决方案2】:

解决方案

  • urls.py
path('investing/<int:pk>/', views.investing, name='investing'),
path('invest/<int:pk>/', views.invest, name='invest'),
  • views.py 只需要包含 JsonResponse,因为我返回的渲染是错误的。
return JsonResponse(
            {
                'message': "success"
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-27
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 2017-08-05
    • 1970-01-01
    相关资源
    最近更新 更多