首页 > 解决方案 > 如何为我的视图添加信号方法?

问题描述

我想计算用户上传的文件数量。我添加了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 在我的情况下不起作用

如何修复我的方法?

标签: django

解决方案


您不需要 send() 方法的“上传”参数。

但是提示,如果您计划对文件上传次数进行持久计数(我认为您很可能是这样),那么我认为您应该创建一个新模型,以便可以将其保存在数据库中。然后您每次保存文档模型时都可以更新该模型。

我建议你看看post_save。祝编码愉快!


推荐阅读