diff --git a/README.md b/README.md index be4cc20..400f653 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ The documentation is organized into the following sections: - **[Quick Start](#quick-start)**: Get up and running quickly with basic setup instructions. - **[API Guide](#api-guide)**: Detailed information on available APIs and endpoints. - **[Usage](#usage)**: How to effectively use the package in your projects. +- **[Examples](#examples)**: Examples of how to configure some key features. - **[Settings](#settings)**: Configuration options and settings you can customize. @@ -976,6 +977,137 @@ No valid audiences found. Please run 'generate_audiences' first. Exiting... ---- +# Examples + +This section provides examples on how to handle various conditions in your project using ``dj-announcement-api``. + +## Assigning New Users to Audiences + +To automatically assign new registered users to specific audiences, `dj-announcement-api` provides several methods. You can use the management commands (``generate_audiences`` and ``generate_profiles``) to assign related users to their appropriate audiences. However, for real-time assignment of new users, automating this within models, serializers, or signals may be more efficient. Below are three recommended approaches for automatic assignment, along with instructions on command usage. + +### Method 1: Using the Model's `save` Method + + +In this approach, user-audience assignments are handled within the model's `save` method of the related model. This method can check if an instance is newly created and, if so, ensures that an `AnnouncementProfile` is generated automatically. + +Steps: +1. Check for the audience corresponding to the model's verbose name, creating it if necessary. +2. Create an `AnnouncementProfile` for the new user associated with the audience. + +```python +from django.db import models +from django_announcement.models import Audience, UserAnnouncementProfile + +class RelatedUserModel(models.Model): + user = models.OneToOneField("User", on_delete=models.CASCADE) + # additional fields + + def save(self, *args, **kwargs): + is_new = self.pk is None + super().save(*args, **kwargs) + + if is_new: + # Retrieve or create the audience based on model name + audience, _ = Audience.objects.get_or_create( + name=self._meta.verbose_name.title() + ) + + # Create the announcement profile for this user + profile, _ = UserAnnouncementProfile.objects.get_or_create( + user=self.user + ) + profile.audiences.add(audience) + profile.save() +``` + +Using this method ensures that each time a user instance is created, audience assignment occurs immediately. + +### Method 2: In the Serializer's `create` Method + +For a more API-focused approach, handle audience assignments directly in the serializer's `create` method. This is ideal when user creation is managed through API endpoints. + +```python + +from rest_framework import serializers +from django_announcement.models import Audience, UserAnnouncementProfile + +class RelatedUserModelSerializer(serializers.ModelSerializer): + class Meta: + model = RelatedUserModel + fields = '__all__' + + def create(self, validated_data): + instance = super().create(validated_data) + + # Fetch or create the audience + audience, _ = Audience.objects.get_or_create( + name=instance._meta.verbose_name.title() + ) + + # Assign the user to the audience + profile, _ = UserAnnouncementProfile.objects.get_or_create( + user=instance.user + ) + profile.audiences.add(audience) + profile.save() + + return instance +``` + +This approach is best for API-based workflows where user creation is handled via serializers. + +### Method 3: Using Signals + +Signals allow handling audience assignments whenever a new user instance is created, keeping assignment logic separate from models and serializers. + +Steps: +1. Create a post-save signal for the user-related model. +2. In the signal, retrieve or create the appropriate audience and announcement profile. + +```python +from django.db.models.signals import post_save +from django.dispatch import receiver +from django_announcement.models import Audience, UserAnnouncementProfile +from .models import RelatedUserModel + +@receiver(post_save, sender=RelatedUserModel) +def assign_audience_to_new_user(sender, instance, created, **kwargs): + if created: + # Retrieve or create audience + audience, _ = Audience.objects.get_or_create( + name=instance._meta.verbose_name.title() + ) + + # Assign user to the audience + profile, _ = UserAnnouncementProfile.objects.get_or_create( + user=instance.user + ) + profile.audiences.add(audience) + profile.save() +``` + +This approach enhances maintainability, particularly when user creation might occur in multiple parts of the codebase. + +## Using Management Commands for Batch Assignment + +If new roles or related models are added and require new audience creation, you can use the management commands: + +1. Run ``generate_audiences`` to create audiences based on related models if they don't already exist. +2. Run ``generate_profiles`` to assign users to these audiences in bulk. + +These commands are useful for batch operations and can be combined with the methods above to automatically assign audiences to new users as they are created. + +## Conclusion + +For automating audience assignments to new users, choose the approach that best suits your workflow: + +- **Model save method** for tightly coupled functionality. +- **Serializer `create` method** for API-driven workflows. +- **Signals** for separation of concerns and modularity. +- **Management commands** for batch assignment and new role or audience generation. + +---- + # Settings This section outlines the available settings for configuring the `dj-announcement-api` package. You can customize these settings in your Django project's `settings.py` file to tailor the behavior of the announcement system to your needs. diff --git a/docs/examples.rst b/docs/examples.rst new file mode 100644 index 0000000..4904e59 --- /dev/null +++ b/docs/examples.rst @@ -0,0 +1,130 @@ +Examples +======== + +This section provides examples on how to handle various conditions in your project using ``dj-announcement-api``. + +Assigning New Users to Audiences +-------------------------------- + +To automatically assign new registered users to specific audiences, `dj-announcement-api` provides several methods. You can use the management commands (``generate_audiences`` and ``generate_profiles``) to assign related users to their appropriate audiences. However, for real-time assignment of new users, automating this within models, serializers, or signals may be more efficient. Below are three recommended approaches for automatic assignment, along with instructions on command usage. + +Method 1: Using the Model's `save` Method +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In this approach, user-audience assignments are handled within the model's `save` method of the related model. This method can check if an instance is newly created and, if so, ensures that an `AnnouncementProfile` is generated automatically. + +Steps: +1. Check for the audience corresponding to the model's verbose name, creating it if necessary. +2. Create an `AnnouncementProfile` for the new user associated with the audience. + +.. code-block:: python + + from django.db import models + from django_announcement.models import Audience, UserAnnouncementProfile + + + class RelatedUserModel(models.Model): + user = models.OneToOneField(User, on_delete=models.CASCADE) + # additional fields + + def save(self, *args, **kwargs): + is_new = self.pk is None + super().save(*args, **kwargs) + + if is_new: + # Retrieve or create the audience based on model name + audience, _ = Audience.objects.get_or_create( + name=self._meta.verbose_name.title() + ) + + # Create the announcement profile for this user + profile, _ = UserAnnouncementProfile.objects.get_or_create(user=self.user) + profile.audiences.add(audience) + profile.save() + +Using this method ensures that each time a user instance is created, audience assignment occurs immediately. + +Method 2: In the Serializer's `create` Method +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +For a more API-focused approach, handle audience assignments directly in the serializer's `create` method. This is ideal when user creation is managed through API endpoints. + +.. code-block:: python + + from rest_framework import serializers + from django_announcement.models import Audience, UserAnnouncementProfile + + + class RelatedUserModelSerializer(serializers.ModelSerializer): + class Meta: + model = RelatedUserModel + fields = "__all__" + + def create(self, validated_data): + instance = super().create(validated_data) + + # Fetch or create the audience + audience, _ = Audience.objects.get_or_create( + name=instance._meta.verbose_name.title() + ) + + # Assign the user to the audience + profile, _ = UserAnnouncementProfile.objects.get_or_create(user=instance.user) + profile.audiences.add(audience) + profile.save() + + return instance + +This approach is best for API-based workflows where user creation is handled via serializers. + +Method 3: Using Signals +~~~~~~~~~~~~~~~~~~~~~~~ + +Signals allow handling audience assignments whenever a new user instance is created, keeping assignment logic separate from models and serializers. + +Steps: +1. Create a post-save signal for the user-related model. +2. In the signal, retrieve or create the appropriate audience and announcement profile. + +.. code-block:: python + + from django.db.models.signals import post_save + from django.dispatch import receiver + from django_announcement.models import Audience, UserAnnouncementProfile + from .models import RelatedUserModel + + + @receiver(post_save, sender=RelatedUserModel) + def assign_audience_to_new_user(sender, instance, created, **kwargs): + if created: + # Retrieve or create audience + audience, _ = Audience.objects.get_or_create( + name=instance._meta.verbose_name.title() + ) + + # Assign user to the audience + profile, _ = UserAnnouncementProfile.objects.get_or_create(user=instance.user) + profile.audiences.add(audience) + profile.save() + +This approach enhances maintainability, particularly when user creation might occur in multiple parts of the codebase. + +Using Management Commands for Batch Assignment +---------------------------------------------- + +If new roles or related models are added and require new audience creation, you can use the management commands: + +1. Run ``generate_audiences`` to create audiences based on related models if they don't already exist. +2. Run ``generate_profiles`` to assign users to these audiences in bulk. + +These commands are useful for batch operations and can be combined with the methods above to automatically assign audiences to new users as they are created. + +Conclusion +---------- + +For automating audience assignments to new users, choose the approach that best suits your workflow: + +- **Model save method** for tightly coupled functionality. +- **Serializer `create` method** for API-driven workflows. +- **Signals** for separation of concerns and modularity. +- **Management commands** for batch assignment and new role or audience generation. diff --git a/docs/index.rst b/docs/index.rst index ec0f759..4cabcff 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -85,6 +85,7 @@ The documentation is organized into the following sections: api_guide usage settings + examples roles contributing diff --git a/docs/usage.rst b/docs/usage.rst index 7037e3c..a6979fd 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -674,3 +674,7 @@ If no related users are found or if audiences are missing, you would see: No users found related to the provided models. No valid audiences found. Please run 'generate_audiences' first. Exiting... + +.. note:: + + Refer to the :doc:`Examples ` section for detailed approaches to automating the assignment of new users to appropriate audiences.