django - 如何为我的视图添加信号方法?
问题描述
我想计算用户上传的文件数量。我添加了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 在我的情况下不起作用
如何修复我的方法?
解决方案
您不需要 send() 方法的“上传”参数。
但是提示,如果您计划对文件上传次数进行持久计数(我认为您很可能是这样),那么我认为您应该创建一个新模型,以便可以将其保存在数据库中。然后您每次保存文档模型时都可以更新该模型。
我建议你看看post_save。祝编码愉快!
推荐阅读
- selenium-webdriver - 在 Testlistener 中读取 XML 参数值
- angular - 如何从 li 级别隐藏父 ul?
- .htaccess - 301 重定向路由 - .htaccess 代码以删除原始路由的附加查询字符串
- java - Java模式匹配器没有相应地分组
- c# - 在 Azure 函数中将 Post 文件转换为 Pdf
- python - cx_Freeze 生成带有 initfsencoding 问题的文件
- scikit-learn - 使用带有管道和 GridSearch 的 cross_val_score 进行嵌套交叉验证
- java - 如何将大数从一个基数转换为另一个基数
- android - Android 上的 EasyPermissions 不授予权限
- javascript - 如何使数组中的元素改变它的位置