【问题标题】:The NoReverseMatch error in Django updateViewDjango updateView 中的 NoReverseMatch 错误
【发布时间】:2020-02-27 14:50:26
【问题描述】:

我正在为我创建的模型编写和更新视图。该模型是一个产品待办列表项。 UpdateView 无法为我的视图找到反向匹配项。 NoReverseMatch 错误表示 Django 找不到匹配的 url 模式。 我的代码如下: 更新PBI视图

class updatePBI(LoginRequiredMixin, UpdateView):
    pk_url_kwarg = 'pbipk'
    kwargs={'pk_url_kwarg': 'pbipk'}
    model = PBI
    fields = ['priority', 'summary', 'story_points', 'effort_hours']
    login_url = '/accounts/login'
    redirect_field_name = '/home'
    template_name = 'backtrack/PBIdetail.html'

    def dispatch(self, request, *args, **kwargs):
        print(kwargs)
        return super().dispatch(request, *args, **kwargs)

    def get_success_url(self):
        return "{}?all=0".format(reverse('pb', kwargs={'pk': self.kwargs['pk']}))

    def get_object(self, queryset=None):        
        obj = get_object_or_404(self.model,pk=self.kwargs['pbipk'])
        return obj

    def form_valid(self, form):

        PBIList = getPBIfromProj(self.kwargs['pk'], '0')
        remove = []
        priorityData = form.cleaned_data['priority']
        if int(priorityData) < self.object.priority:
            # Remove all PBI with priority higher than post data priority
            # and lesser  or equal than current PBI priority
            for PBIObj in PBIList:
                if PBIObj.priority < int(priorityData) or PBIObj.priority >= self.object.priority:
                    remove.append(PBIObj.priority)
            PBIList = [
                PBIObj for PBIObj in PBIList if PBIObj.priority not in remove]
            # Increase each objects priority by one
            for PBIObj in PBIList:
                PBIObj.priority += 1
                PBIObj.save()
        else:
            # Remove all PBI with priority higher than post PBI priority
            # and lesser than and equal to Post data priority
            for PBIObj in PBIList:
                if PBIObj.priority <= self.object.priority or PBIObj.priority > int(priorityData):
                    remove.append(PBIObj.priority)
            PBIList = [
                PBIObj for PBIObj in PBIList if PBIObj.priority not in remove]
            # Decrease each objects priority by one
            for PBIObj in PBIList:
                PBIObj.priority -= 1
                PBIObj.save()

        return super().form_valid(form)

模型.py

from django.urls import reverse

# Create your models here.

class PBI(models.Model):
    status = models.CharField(max_length=1,
                              choices=[("N", "Not Done"), ("P", "In Progress"), ("D", "Done")], default="N")
    story_points = models.FloatField()
    effort_hours = models.FloatField()
    summary = models.TextField(default = None)
    priority = models.IntegerField(default=0)
    Project = models.ForeignKey('Project', on_delete=models.CASCADE, related_name='pbi')

    def __str__(self):
        return self.summary

    class Meta:
        db_table = "PBI"
        verbose_name = 'PBI'
        verbose_name_plural = 'PBIs'


class Project(models.Model):
    name = models.CharField(max_length=256)

    def __str__(self):
        return self.name

    class Meta:
        db_table = "Project"

urls.py

from django.conf.urls import url
from backtrack import views
from django.shortcuts import redirect

urlpatterns = [
    path('', lambda x: redirect('1/'),name='home'),
    path('<int:pk>/', views.HomeView.as_view(),name = 'home-project'),
    path('<int:pk>/pb/', views.ProductBacklogView.as_view(),name='pb'),
    path('<int:pk>/pb/add/', views.AddPBI.as_view(),name='add'),
    path('<int:pk>/pb/<int:pbipk>/update', views.updatePBI.as_view(),name='detail'),
    path('<int:pk>/pb/<int:pbipk>/delete', views.DeletePBI.as_view(),name='delete')
]

产品待办事项页面

{% block content %}
    <h1 class="page-header"><i class="fa fa-file"></i> Product BackLog</h1>
    <div class="row placeholders"></div>
    {% if data|length == 0 %}
        <h4>There are no PBIs</h4>
    {% endif %}
    <h2 class="sub-header">
        <div class="dropdown">
            <button class="btn btn-light dropdown-toggle pull-left" type="button" data-toggle="dropdown" style="margin-bottom: 10px;">Filter By
                <span class="caret"></span></button>
                <ul class="dropdown-menu">
                    <li><a href="#">Priority</a></li>
                    <li><a href="#">Story Points</a></li>
                    <li><a href="#">Effort Hours</a></li>
                </ul>
                <div class="btn-group btn-toggle">
                    <button class="btn btn-xs btn-primary active toggle">NOT DONE</button>
                    <button class="btn btn-xs btn-default toggle">ALL</button>
                </div>
                <button type="button" class="btn btn-light" style="margin-bottom: 10px;"><a href="{% url 'add' pk=1 %}" style="text-decoration: none; color: black"><i class="fa fa-plus" id="A"></i>ADD</a></button>
                <button type="button" class="btn btn-light" style="margin-bottom: 10px;"><i class="fa fa-times" id="A"></i>DELETE</button>
        </div>
    </h2>
    <div class="table-responsive">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th> </th>
                    <th>Priority</th>
                    <th>Summary</th>
                    <th>Status</th>
                    <th>Story Points</th>
                    <th>Cumulative Story Points</th>
                    <th>Effort hours</th>
                    <th>Cumulative Effort hours</th>
                </tr>
            </thead>
            <tbody>
                {% for PBI in data %}
                    <tr>
                    <td><input type="checkbox"></td>
                    <td>
                    {% if PBI.status == "N" %}
                        {{PBI.priority}}
                    {% else %}
                        --
                    {% endif %}
                    </td>
                    <td><a style="text-decoration: none; color: cornflowerblue;" href={% url 'detail' pk=1 pbipk=PBI.id %}>{{PBI.summary}}</a></td>
                    <td>
                    {% if PBI.status == "N" %}
                        Not Done
                    {% elif PBI.status == "P" %}
                        In Progress
                    {% else %}    
                        Done
                    {% endif %}
                    </td>
                    <td>{{PBI.story_points}}</td>
                    <td>{{PBI.sum_story_points}}</td>
                    <td>{{PBI.effort_hours}}</td>
                    <td>{{PBI.sum_effort_hours}}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    <script>
    $.urlParam = function (name) {
            var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

            return (results !== null) ? results[1] || 0 : false;
        }
    $(document).ready(function () {
        if($.urlParam('all') == '1'){
            $(this).find('.toggle').toggleClass('active');  

            if ($(this).find('.btn-primary').length>0) {
                $(this).find('.toggle').toggleClass('btn-primary');
            }
        }
        var getUrl = window.location;
        var baseUrl = getUrl.protocol + "//" + getUrl.host + getUrl.pathname;
        $('.btn-toggle').click(function(){
            console.log($.urlParam('all') == '0')
            if($.urlParam('all') == '0')
                window.location.replace(baseUrl + "?all=1");
            else
                window.location.replace(baseUrl + "?all=0");
        })

    });
    </script>
{% endblock content %}

我收到了这个错误

NoReverseMatch at /home/1/pb/50/update
Reverse for 'detail' with keyword arguments '{'pk': 1, 'pbipk': ''}' not found. 1 pattern(s) tried: ['home/(?P<pk>[0-9]+)/pb/(?P<pbipk>[0-9]+)/update$']

更新 我发现错误是因为我正在使用 PBI.id 设置表单操作,但更新视图没有将 PBI 传递给我的模板。我该如何解决这个问题?

【问题讨论】:

标签: django python-3.x django-class-based-views


【解决方案1】:

好的。我发现我做错了什么。在调用 super().get_context_data(form) 之后,我必须重写模板视图 mixin 的 get_context_data() 函数并在上下文中传递 PBI。

【讨论】:

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