Adarsh D
Adarsh D

Reputation: 581

save() missing 1 required positional argument: 'self' Error while using Django Signal Dispatcher

models.py

class es_event(models.Model):
    #some attributes
    reg_applicants = models.FilePathField(path=None)
    ev_admin =  models.ForeignKey('es_user',related_name='events',on_delete=None)
    slug = models.SlugField(max_length=250)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.ev_name)
        return super(es_event, self).save(*args, **kwargs)

    def get_absolute_url(self):
            return reverse('event_detail', kwargs={'id': self.id, 'slug': self.slug })

views.py

class CreateEventView(LoginRequiredMixin,CreateView):
    login_url = "/login/"
    model = es_event
    fields = ['ev_name','ev_venue','ev_description','ev_date','registrant_name','registrant_age','registrant_phone','registrant_email','registrant_institution']
    def form_valid(self, form):
        form.instance.ev_admin = self.request.user.es_user
        return super(CreateEventView, self).form_valid(form)

Now when a new row is added to es_event. I want to set the reg_applicants field with a path(including filename)

eg: if es_event.id is 5 then filename should be Registered_5.csv

To do that I created this Signal in models.py

@receiver(post_save, sender=es_event)
def set_csv_path(sender, **kwargs):
    rel_path = "reg_csv/Registered_{}.csv".format(sender.id)
    path = os.path.join(settings.MEDIA_ROOT,rel_path)
    sender.reg_applicants = path
    sender.save()# error statement

which gives me this error

save() missing 1 required positional argument: 'self'

I think there is something wrong with the signal dispatcher function set_csv_path(). I don't know what it is

Upvotes: 3

Views: 2802

Answers (2)

Shamsul Arefin
Shamsul Arefin

Reputation: 1917

I also had the similar problem, turns out that the arguments of the receiver method cannot be renamed, you have to keep the original name as it is. in my case my receiver was something like this, def my_receiver(sender, my_instance, created, **kwargs). I had to change to (sender, instance, created, **kwargs)

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599490

You're using the wrong parameter. sender is the class to which the signal is connected. You need to also accept the instance parameter .

@receiver(post_save, sender=es_event)
def set_csv_path(sender, instance, **kwargs):
    rel_path = "reg_csv/Registered_{}.csv".format(instance.id)
    path = os.path.join(settings.MEDIA_ROOT,rel_path)
    instance.reg_applicants = path
    instance.save()

Upvotes: 3

Related Questions