Using Signals to create data in a Django project once a boolean is changed

Viewed 33

I have a question regarding signals. So I have the following model that has a boolean defaulted as False. Once the user clicks on a button to make it true I want to create objects in another model. Here is what I have done but did not create or make any changes:

Here is the Initial Model:

class Initial_Model(models.Model):
    active = models.BooleanField(default=False)

Here is the model that I want to create objects once the Initial_Model active boolean becomes True:

class ActiveSession(models.Model):
    start_date = models.DateTimeField(auto_now_add=True,blank=True, null=True)
    end_date = models.DateTimeField(auto_now_add=True,blank=True, null=True)

@receiver(post_save, sender=Initial_Model)
def create_session(sender, instance, **kwargs):
    if Initial_Model.active == True:
        ActiveSession.objects.create()

Here is the views.py:

def change_status(request, id):
    if request.is_ajax() and request.method == 'POST':
        initial_model = Initial_Model.objects.get(id=id)
        if request.POST.get('active') == 'true':
            initial_model.active = True
            initial_model.save()
            context = {
                'initial_model': initial_model,
                'id': initial_model.id,
                'status': 'success',
                'active': ''
            }
            html = render_to_string('app/name.html', context,request=request)
            start_session= timezone.now()
            return JsonResponse({'form': html}) 

My question is this the correct way of creating the instances in a model. What am I doing wrong and how to fix it.

My required outcome is that when the Initial_Model boolean is switched from False to True a new ActiveSession is added

Using the code below from here is the traceback:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in in
ner
    response = get_response(request)
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_r
esponse
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\User\Desktop\Gym_App\my_gym\views.py", line 36, in change_status
    initial_model.save()
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\base.py", line 753, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\base.py", line 777, in save_base
    pre_save.send(
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\dispatch\dispatcher.py", line 177, in send
    return [
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\dispatch\dispatcher.py", line 178, in <list
comp>
    (receiver, receiver(signal=self, sender=sender, **named))
  File "C:\Users\User\Desktop\Gym_App\my_gym\models.py", line 70, in create_session
    obj = sender.objects.get(instance.id)
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_
method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\query.py", line 418, in get
    clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\query.py", line 942, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\query.py", line 962, in _filter_o
r_exclude
    clone._filter_or_exclude_inplace(negate, *args, **kwargs)
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\query.py", line 969, in _filter_o
r_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\sql\query.py", line 1360, in add_
q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\sql\query.py", line 1379, in _add
_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\sql\query.py", line 1257, in buil
d_filter
    arg, value = filter_expr
TypeError: cannot unpack non-iterable int object
1 Answers

you can implement your signal like this:

@receiver(pre_save, sender=Initial_Model)
def create_session(sender, instance, **kwargs):
    obj = sender.objects.get(id=instance.id)
    if not obj.active and obj.active != instance.active
        ActiveSession.objects.create()
Related