代码之家  ›  专栏  ›  技术社区  ›  Ben2pop

NoReverseMatch与键参数不匹配

  •  0
  • Ben2pop  · 技术社区  · 6 年前

    我有一个让我抓狂的响应错误,我尝试了所有方法,但没有找到为什么我会出现这个错误:

    django.urls.exceptions.NoReverseMatch: Reverse for 'team_select' with keyword arguments '{'pk1': ''}' not found.
    1 pattern(s) tried: ['website/project/(?P<pk1>[0-9]+)/linkteam2/$']
    

    这就是我的观点:

    class HomePage(TemplateView):
        template_name= 'index.html'
    
    class LinkTeam(generic.ListView):
        template_name = 'link_project.html'
    
        def get_queryset(self):
            #import pdb; pdb.set_trace()
            #team2 = Team.objects.all().filter(team_hr_admin = self.request.user)
            queryset = Team.objects.filter(team_hr_admin=self.request.user)
            return queryset
    
    def TeamSelect(request):
        import pdb; pdb.set_trace()
        if request.method == "POST":
            select_form = EditSelectTeam(request.user, request.POST)
            if select_form.is_valid():
                data = select_form.cleaned_data['team_choice']
                obj2 = Project.objects.filter(project_hr_admin=request.user)
                obj3 = obj2.latest('id')
                if obj3.team_id == None:
                    obj3.team_id = data
                    obj3.save()
                    obj4 = obj3.team_id
                    obj5 = obj4.members.all()
    
                    for i in obj5:
                        current_site = get_current_site(request)
                        message = render_to_string('acc_join_email.html', {
                            'user': i.first_name,
                            'domain':current_site.domain,
                            })
                        mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app'
                        to_email = i.email
                        email = EmailMessage(mail_subject, message, to=[to_email])
                        email.send()
                    messages.success(request, 'test')
                    return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk':obj3.id}))
                else:
                    print('this project has already a team')
            else:
                print('Non Valid form')
    
        else:
            select_form = EditSelectTeam(request.user)
        return render(request,'link_project.html',
                                {'select_form':select_form })
    
    class HRIndex(generic.ListView):
        #import pdb; pdb.set_trace()
        template_name = "HR_index.html"
        model = Project
    
    class CandidateIndex(TemplateView):
        #import pdb; pdb.set_trace()
        template_name = "candidate_index.html"
    
    class EmployeeIndex(TemplateView):
        #import pdb; pdb.set_trace()
        template_name = "employee_index.html"
    
        def get_context_data(self, **kwargs):
            context = super(EmployeeIndex, self).get_context_data(**kwargs)
            surveys = Survey.objects.filter(is_published=True)
            if not self.request.user.is_authenticated():
                surveys = surveys.filter(need_logged_user=False)
            context['surveys'] = surveys
            return context
    
    class ProjectCreate(LoginRequiredMixin,CreateView):
        model = Project
        fields = ['name']
        template_name = 'project_form.html'
    
        def form_valid(self, form):
            form.instance.project_hr_admin = self.request.user
            return super(ProjectCreate, self).form_valid(form)
    
    class ProjectDetailView(LoginRequiredMixin,generic.DetailView):
        #import pdb; pdb.set_trace()
        model = Project
        template_name = 'project_details.html'
    
        def get_object(self, queryset=None):
            return get_object_or_404(Project,id=self.kwargs['pk1'])
    
        def get_context_data(self, **kwargs):
            context = super(ProjectDetailView, self).get_context_data(**kwargs)
            try:
                team_name = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all()
                context['team_name'] = team_name
            except AttributeError:
                pass
            return context
    
    class EmployeeDetailView(LoginRequiredMixin, generic.DetailView):
        #import pdb; pdb.set_trace()
        model = MyUser
        template_name = 'Employee_Details.html'
    
    
        def get_object(self, queryset=None):
            return get_object_or_404(MyUser, pk=self.kwargs['pk2'], members__project=self.kwargs['pk1'])
    
        def get_context_data(self, **kwargs):
            context = super(EmployeeDetailView, self).get_context_data(**kwargs)
            employee_name = MyUser.objects.get(id=self.kwargs['pk2'])
            team_list = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all()
            team_list_pop = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all().exclude(id=self.kwargs['pk2'])
    
            context={
                'employee_name' : employee_name,
                'team_list' : team_list,
                'team_list_pop' : team_list_pop
            }
            return context
    
    class TeamCreate(CreateView):
    
        model = Team
        fields = ['team_name']
        template_name = 'team_form.html'
    
        def form_valid(self, form):
            #import pdb; pdb.set_trace()
            valid = super(TeamCreate, self).form_valid(form)
            form.instance.team_hr_admin = self.request.user
            obj = form.save()
            #SELECT * FROM project WHERE user = 'current_user' AND team_id = NULL
            obj2 = Project.objects.get(project_hr_admin=self.request.user, team_id=None)
            obj2.team_id = obj
            obj2.save()
            return valid
            return super(TeamCreate, self).form_valid(form)
    
        def get_success_url(self):
            #import pdb; pdb.set_trace()
            project = Project.objects.get(team_id=None, project_hr_admin=self.request.user)
            return project.get_absolute_url()
    

    URL:

    from django.conf.urls import url, include
    from website import views
    
    app_name = 'website'
    urlpatterns = [
        url(r'^hr_index/$', views.HRIndex.as_view(), name='hr_index'),
        url(r'^candidate_index/$', views.CandidateIndex.as_view(),name='candidate_index'),
        url(r'^employee_index/$', views.EmployeeIndex.as_view(),name='employee_index'),
        url(r'^addproject/$', views.ProjectCreate.as_view(), name='add_project'),
        url(r'^project/(?P<pk1>[0-9]+)/addteam/$', views.TeamCreate.as_view(), name='add_team'),
        url(r'^project/(?P<pk1>[0-9]+)/linkteam/$', views.LinkTeam.as_view(), name='link_team'),
        url(r'^project/(?P<pk1>[0-9]+)/linkteam2/$', views.TeamSelect, name='team_select'),
        url(r'^project/(?P<pk1>[0-9]+)/$',views.ProjectDetailView.as_view(), name='ProjectDetails'),
        url(r'^project/(?P<pk1>[0-9]+)/api/chart/data2/$',views.TeamChartData.as_view(), name='TeamChartData'),
        url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.EmployeeDetailView.as_view(), name='EmployeDetails'),
        url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/api/chart/data/$',views.EmployeeChartData.as_view(), name='EmployeeChartData'),
        #url(r'^project/(?P<pk>[0-9]+)/api/chart/data/$', views.ChartData.as_view(), name='chartdata'),
    
    ]
    

    关键字参数表示pk1为空,但它不应该为空,因为我在页面中 http://127.0.0.1:8000/website/project/2/

    我的模板看起来像。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

    {% load static %}
    <div class="invite-team">
      <div class="jumbotron greenback">
        <div class="jumbo-text">
          <h7>Your project has been created, It is time to link a team or create a new for your project</h3>
        </div>
          <div class="jumbo-button">
            <a href="{% url 'website:team_select' pk1=project.id %}" class="btn btn-secondary" role="button"><span class="fa fa-link"></span>   Link an existing team</a>
            <a href="{% url 'website:add_team' pk1=project.id %}" class="btn btn-success" role="button"><span class="fa fa-plus-circle"></span>   Create a new team</a>
          </div>
      </div>
    </div>
    

    编辑: 添加以下内容后出现错误:

    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'project_details.html'
    
    
    class TeamChartData(APIView):
        queryset = MyUser.objects.all()
        serializer_class = MyUserSerializer, #ProjectSerializer
        permission_classes = []
        http_method_names = ['get',]
        renderer_classes = [TemplateHTMLRenderer]
        template_name = 'project_details.html'
    
    
        def get_serializer_class(self):
            return self.serializer_class
    
    
        def get(self, request, format=None, *args, **kwargs):
            chunk_team = get_team_info_score(self)
            motiv_team = get_team_motivation_score(self)
            action_team = get_team_action_score(self)
            behav_team = get_behaviour_action_score(self)
            team_complete = get_team_complete_data(self)
            cohesiveness_score = get_team_cohesivenss_score(self)
            info_dist = get_question_similarities(self)[0]
            motiv_dist = get_question_similarities(self)[1]
            action_dist = get_question_similarities(self)[2]
            behav_dist = get_question_similarities(self)[3]
    data = {
                "team_info_score":chunk_team,
                "team_motiv_score":motiv_team,
                "team_action_score":action_team,
                "team_behaviour_score":behav_team,
                "team_complete":team_complete,
                "cohesiveness_score":cohesiveness_score[0],
                "users":cohesiveness_score[1],
                "user_dist":cohesiveness_score[2],
                "info_dist":info_dist,
                "motiv_dist": motiv_dist,
                "action_dist":action_dist,
                "behav_dist":behav_dist,
                "complete_label":complete_label,
    
                "info_label":processing_information_label,
                "motivation_label": motivation_label,
                "action_label":action_label,
                "behav_label":other_data_label,
    
            }
            return Response(data)
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   dvnguyen    6 年前

    您的url反向看起来很好。问题是你没有设置 project 根据您的上下文 ProjectDetailView :

    def get_context_data(self, **kwargs):
        context = super(ProjectDetailView, self).get_context_data(**kwargs)
        try:
            project = Project.objects.get(id=self.kwargs['pk1'])
            team_name = project.team_id.members.all()
            context['team_name'] = team_name
            context['project'] = project
        except AttributeError:
            pass
        return context