Richard Rublev
Richard Rublev

Reputation: 8172

How to add signal method for my view?

I want to count how may files the user has uploaded. I have added signals.py

from django.dispatch import Signal

upload_completed = Signal(providing_args=['upload'])

And 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

to my project.

My views upload

@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}) 

This effort does not work.I got

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

I found signal example 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,
        )

But it seems to me that classmethod would not work in my case

How to fix my method?

Upvotes: 0

Views: 273

Answers (1)

Adam
Adam

Reputation: 46

You don't need the 'uploads' argument for the send() method.

But a tip, if you're planning on a persistent count of the number of file uploads (which I assume you most likely are), then I think you should create a new model so that you can save it in your database.Then you can update that model every time a Document model is saved.

And I suggest you have a look at post_save. Have a nice day coding!

Upvotes: 1

Related Questions