Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

📚 Docs/examples #57

Merged
merged 3 commits into from
Oct 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 132 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.


Expand Down Expand Up @@ -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.
Expand Down
130 changes: 130 additions & 0 deletions docs/examples.rst
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ The documentation is organized into the following sections:
api_guide
usage
settings
examples
roles
contributing

Expand Down
4 changes: 4 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <examples>` section for detailed approaches to automating the assignment of new users to appropriate audiences.