I'm new to Django and watching a series of tutorial videos where we did a project ... In the series they talk about 'signals'.
What is proposed to do is connect some signals at the time of making a user registration on the page
views.py
from django.shortcuts import render, redirect
from .models import *
from .forms import OrderForm, CustomerForm, CreateUserForm
from django.contrib import messages
from django.contrib.auth.models import Group
from django.contrib.auth.decorators import login_required
from .decorators import unauthenticated_user, allowed_users, admin_only
@unauthenticated_user
def registerPage(request):
form_value = CreateUserForm
if request.method == 'POST':
form_value = CreateUserForm(request.POST)
if form_value.is_valid():
user = form_value.save()
username = form_value.cleaned_data.get('username')
messages.success(request, 'Account was create for {}'.format(username))
return redirect('login')
else:
messages.warning(request, 'Data is invalid, please try again')
context = {'form_key':form_value}
return render(request, 'accounts/register.html', context)
signals.py
from django.db.models.signals import post_save
from django.contrib.auth.models import User, Group
from .models import Customer
def customer_profile(sender, instance, created, **kwagrs):
if created:
group = Group.objects.get(name='customer')
instance.groups.add(group)
Customer.objects.create(
user = instance,
name = instance.username
)
print('Profile created.!')
post_save.connect(customer_profile, sender= User)
apps.py
from django.apps import AppConfig
class AccountsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'accounts'
def ready(self):
import accounts.signals
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
'django_filters',
]
This are my questions:
What is the job of the 'ready()' function in 'apps.py'?
The tutorial suggests placing 'accounts.apps.AccountsConfig' in the 'settings.py' file specifically in the 'INSTALLED_APPS' section, is it necessary to place it?
Another method suggested by the tutorial is to place default_app_config = 'accounts.apps.AccountsConfig' in the file 'init.py' .. Which is the most recommended?
The use of these signals seems super practical to develop the functionality of a project in the best way. That is why I want to understand these things as clearly as possible, thank you very much for your help