首页 > 解决方案 > /invest/(?P1\d+)/ 处的 Django 错误 NoReverseMatch

问题描述

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
        <a href="{% url 'invest' pk=marking.id %}";><button type="button" class="btn btn-primary" data-toggle="modal" >Invest</button></a>

<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>
path('invest/(?P<pk>\d+)/', views.invest, name='invest'),
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})

标签: pythondjangoajax

解决方案


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

from django.conf.urls import url

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

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


推荐阅读