代码之家  ›  专栏  ›  技术社区  ›  Richard Rublev

如何为我的视图添加信号方法?

  •  0
  • Richard Rublev  · 技术社区  · 7 年前

    我想计算一下用户上传的文件数量。 我添加了signals.py

    from django.dispatch import Signal
    
    upload_completed = Signal(providing_args=['upload'])
    

    和summary.py

    from django.dispatch import receiver
    from .signals import upload_completed
    
    @receiver(charge_completed)
        def increment_total_uploads(sender, total, **kwargs):
            total_u += total
    

    我的项目。

    我的视图上载

    @login_required
    def upload(request):
        # Handle file upload
        user = request.user
        if request.method == 'POST':
            form = DocumentForm(request.POST, request.FILES)
            if form.is_valid():
                newdoc = Document(docfile=request.FILES['docfile'])
                newdoc.uploaded_by = request.user.profile
                upload_completed.send(sender=self.__class__, 'upload')
                #send signal to summary
                newdoc.save()
                # Redirect to the document list after POST
                return HttpResponseRedirect(reverse('upload'))
        else:
            form = DocumentForm()  # A empty, unbound form
    
        # Load documents for the upload page
        documents = Document.objects.all()
    
        # Render list page with the documents and the form
        return render(request,'upload.html',{'documents': documents, 'form': form}) 
    

    这种努力不起作用。我

        upload_completed.send(sender=self.__class__, 'upload')
                                                    ^
    SyntaxError: positional argument follows keyword argument
    

    我找到信号的例子 testing-django-signals

    from .signals import charge_completed
    @classmethod
    def process_charge(cls, total):
        # Process charge…
        if success:
            charge_completed.send_robust(
                sender=cls,
                total=total,
            )
    

    但在我看来,classmethod在我的情况下是行不通的

    如何解决我的方法?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Adam    7 年前

    send()方法不需要'uploads'参数。

    但是有一个提示,如果你计划持续计算文件上传的次数(我想你很可能是这样),那么我认为你应该创建一个新的模型,这样你就可以将它保存在数据库中,然后你就可以在每次保存文档模型时更新该模型。

    我建议你看看 post_save 是的。祝你今天编码愉快!