i m doing some project using django frame work i am a beginner and just used
django signals but i m confused that why do we need to imporrt signals file in app.py inside the ready function
code below makes question more clear i m stuck in this so require help
signal.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile
#receiver(post_save,sender=User)
def create_profile(sender,instance,created,**kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save,sender=User)
def save_profile(sender,instance,**kwargs):
instance.profile.save()
app.py
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
#i have no idea what this function does
what is the need of ready function here and why is it importing signals here???
what if i import signals at the top without using ready function??
what is the need of ready function here and why is it importing signals here?
The ready() method [Django-doc] is called after the registry is fully loaded. You thus can then perform some operations you want to perform before the server starts handling requests. This is specified in the documentation:
Subclasses can override this method to perform initialization tasks such as registering signals. It is called as soon as the registry is fully populated.
The reason the signals are imported here is because Django will not import the signals if you do not import those explicitly. If the signals module is not imported, then the signals are not registered on the corresponding models, and hence if you for example make changes to your User model, the signals will not be triggered.
Usually one adds a #noqa comment to the import line, to prevent a linter tool like pylint to raise warnings about an import that you do not use.
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals # noqa
Related
I am trying to add a user to a group when the user is created. I have seen a few different ways to accomplish similar things with signals but nothing I am trying has seemed to work.
In the shell, I ran Group.objects.get(name='User') to make sure that the group was being recognized.
signals.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User, Group
from django.dispatch import receiver
#receiver(post_save, sender=User)
def add_user_to_user_group(sender, instance, created, **kwargs):
try:
if created:
instance.groups.add(Group.objects.get(name='User'))
except Group.DoesNotExist:
pass
This part I am very unsure of, I have seen a few different ways people have done this part. One tutorial did it this way but I am not sure what just importing the signals would do
app.py
from django.apps import AppConfig
class UserConfig(AppConfig):
name = 'User'
def ready(self):
import User.signals
I'm trying to assign a group to every new user registered into the system. I've already read something about it in another questions but I don't really know where to add the necessary code to make it work.
I'm using Django 2.1.3 and I'm logging users using allauth (social login, but it shouldn't make any difference as a new instance in the User table is created)
You can use a #post_save signal for example that, each time a User is created, adds the given group to the groups of the User. Typically signals reside in a file named handlers.py in the signals directory of an app, so you probably should create or modify the files listed in boldface:
app/
signals/
__init__.py
handlers.py
__init__.py
apps.py
...
# app/signals/handlers.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from django.contrib.auth.models import Group
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def save_profile(sender, instance, created, **kwargs):
if created:
g1 = Group.objects.get(name='group_name')
instance.groups.add(g1)
where group_name is the name of the group you want to add.
You should then import the handlers.py module in your MyAppConfig (create one if you do not have constructed such config yet):
# app/apps.py
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'app'
verbose_name = "My app"
def ready(self):
import app.signals.handlers
and register the MyAppConfig in the __init__.py of the app:
# app/__init__.py
default_app_config = 'app.apps.MyAppConfig'
If this should happen for any new User instance, you can connect a handler to the post_save signal:
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=User)
def handle_new_job(sender, **kwargs):
if kwargs.get('created', False):
user = kwargs.get('instance')
g = Group.objects.get(name='whatever')
user.groups.add(g)
Include this code in your app and make sure it is imported as stated e.g. here.
I have a script called helpers.py in my Django app in which I can't import models because it creates a circular reference.
As a workaround to this problem, I tried loading the modules dynamically in the script, like so:
from django.apps import apps
MyModel=apps.get_model("mymodule", "MyModel")
but this gets called before Django loads models and throws an error.
Is there a way around this problem?
Ideally I need to be able to create references to the model after Django has initialised the models, so that its available throughout the script, but I'm not sure if this is possible.
Are you sure you need models inside your helpers.py? If needed stuff is related to a model consider implementing this as a model method or a custom manager.
If you are sure you need models in your helpers.py, then look at the examples below.
As #Selcuk mentioned you can try a local import in a function of the helpers.py. This example works even if helpers.py is imported in the models.py:
# helpers.py
def foo():
from .models import MyModel
# do something with MyModel
On the top of your helpers.py which has a circular import of the models.py you can import the whole models module without specifying the names you want to import from it. So the next example works too:
# helpers.py
import myapp.models
def foo():
# do something with myapp.models.MyModel
But the next doesn't work, because we specify the name from the module (that may be not defined yet):
# helpers.py
from .models import MyModel
# ImportError is risen when you import a name from the module which has a circular import of this module
def foo():
# do something with MyModel
And this doesn't work too. It will import the module, but when you try to access the name MyModel you will get NameError:
# helpers.py
from .models import *
def foo():
# do something with MyModel
# NameError is risen when you do something with MyModel here
Sitting over a day on it. Really can't understand why this signal is not triggered when a user is activated, no error log, no exception in the admin on activation. Can anybody help? The following code should result in a log message in the apache error.log when a user, right?
import logging
from django.dispatch import receiver
from registration.signals import user_activated
#receiver(user_activated)
def registered_callback(sender, **kwargs):
logger = logging.getLogger("user-activated")
logger.error("activated here")
same with user_registered
First of all im using django 1.8.3 .You should register your signal first. As far as i know, there are some methods to do that but this is what im doing;
Create signals.py in your app write your signal there;
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=your_model,dispatch_uid="yourmodel_save_receiver")
def post_save_yourmodel(sender, instance, **kwargs):
if instance.profile_status:
print "active"
else:
print "not active"
Then you should create apps.py. This file contains configuration information to your model.
from django.apps import AppConfig
class yourmodel_config(AppConfig):
name = 'yourmodel_config'
verbose_name = 'your_model config'
def ready(self):
import yourmodel.signals
With this whenever your app is ready, your signals will be imported
Finally open your __init__.py and add the following.
default_app_config = 'yourmodel.apps.yourmodel_config'
With this you are defining application configuration for your model.This example when ever yourmodel is saved, signal checks for profile_status attribute and prints output depending on the value(true or false) to your console. You can also add created parameter to your model to know that if instance of the model is created. created will return True if a new record was created. def post_save_yourmodel(sender, instance, created, **kwargs):. Otherwise this signal will be triggered whenever your model is saved with yourmodel.save().
Consider that is a post_save example.You can find list of the model signals from here.
I'm trying to setup a signal so that when a valid form is saved, a function is ran to carry out a related task.
My app structure is as follows;
- events
- helpers
- __init__.py
- status.py
- models
- signals
- __init__.py
- event.py
- __init__.py
- event.py
- status.py
- views
- __init__.py
- event.py
I believe signals need to be imported as early as possible, before models, so at the top of models/__init__.py I've got from .signals import *.
# views/event.py
class AddEventView(CreateView):
"""
View for adding an Event.
"""
model = Event
form_class = EventForm
success_url = reverse_lazy('events:all_events')
def form_valid(self, form):
self.object = form.save()
signals.event_status.send(
sender=None, request=self.request, event=self.object, status=None
) # Should the sender be self.object?
return super(AddEventView, self).form_valid(form)
# signals/event.py
from django.dispatch import Signal
event_status = Signal(providing_args=["request", "event", "status"])
# helpers/status.py
from ..models import Status, StatusHistory
from ..models.signals import event_status
def create_status(sender, **kwargs):
"""
Create a status for a given event.
"""
event = kwargs['event']
status = kwargs['status']
creator = User.objects.get(pk=event.creator)
try:
current_status = StatusHistory.objects.filter(
event=event).order_by('timestamp')[0]
except IndexError:
# Not sure what we're doing here yet.
pass
if not status:
status = Status.objects.get(description=_("Submitted"))
statushistory = StatusHistory.create(
event=event,
event_status=status,
user=creator
)
statushistory.save()
event_status.connect(create_status)
I'm running the debug server in Pycharm with a break point in the create_status() function & it's never getting hit.
Have I implemented this wrong?
I've used signals in some of my projects and I allways import the signals in the __init__.py of my Django APP (Same folder as settings.py, views.py, urls.py...)
__init__.py:
import signals
signals.py:
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from my_project.models import *
#receiver(post_save, sender=Modelname) # Called after an object is saved
def create_modelname(sender, **kwargs):
obj = kwargs['instance'] # I get the object being saved here
# ... Here I do whatever I want
#receiver(pre_delete, sender=Modelname) # Called before an object is deleted
def delete_modelname(sender, **kwargs):
obj = kwargs['instance']
# ... Do whatever you need
Remember this 2 imports:
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
Remember to import the signals
To import the signals you need to add import signals in your __init__.py of your project
Using this code, this functions are called automatically by Django when an object of the class Modelname is created or deleted.
The receiver for created object is called after the object is created, and the receiver for deleted object is called before the object is deleted.
I think maybe you just need to import your helpers/status.py eg in models/__init__.py
otherwise your event_status signal gets defined ok but the signal handler create_status never gets connected by Django
if you only have one handler for that signal it might make sense to put it in the same module as the signal definition
I found one case that signal is not working.
Here are cases that signal(pre_save, post_save) won't happen.
Model.objects.filter(pk=pk).update(key=value)
Bulk model functions won't happen signals.