pinax-referrals

repository·master·Indexed 42 days ago

https://github.com/pinax/pinax-referrals

A Django application for managing referral links and tracking user responses to facilitate marketing and social sharing. It supports generating referral links for specific objects or anonymous codes, recording user activity via Referral.record_response, and linking responses to users through the user_linked_to_response signal. Compatible with Django 3.2, 4.2, 5.2, and 6.0 across Python 3.8 to 3.13.

Tokens
2.1K
Snippets
5
Records
9
Agent score
3%

What's inside pinax-referrals

  1. Overview of pinax-referrals

    master

    pinax-referrals allows a Django site to publish referral links to specific pages or objects and record responses to those links.

    Key capabilities include:

    • Generating referral links for specific objects (e.g., a link on a detail page that a user can share via social media).
    • Recording responses to referral codes to track user activity associated with a specific referral.
    • Generating anonymous referral links/codes, which is useful for marketing promotions.
  2. Install pinax-referrals

    master

    To install pinax-referrals, use pip to install the package, add it to your INSTALLED_APPS, configure the middleware, and include the URLs in your project's URL configuration.

    1. Install the package:

      pip install pinax-referrals
    2. Update INSTALLED_APPS:

      INSTALLED_APPS = [
          # other apps
          "pinax.referrals",
      ]
    3. Configure Middleware: Add pinax.referrals.middleware.SessionJumpingMiddleware to your MIDDLEWARE setting. It must be placed after django.contrib.auth.middleware.AuthenticationMiddleware to correctly link users who register/authenticate after clicking a referral link.

      MIDDLEWARE = [
          # other middleware
          "django.contrib.auth.middleware.AuthenticationMiddleware",
          "pinax.referrals.middleware.SessionJumpingMiddleware",
      ]
    4. Include URLs: Add pinax.referrals.urls to your urlpatterns using a namespace.

      urlpatterns = [
          # other urls
          url(r"^referrals/", include("pinax.referrals.urls", namespace="pinax_referrals")),
      ]
    pip install pinax-referrals
  3. Configure pinax-referrals settings

    master

    Modify the default behavior of pinax-referrals using the following settings:

    SettingDefaultDescription
    PINAX_COOKIE_MAX_AGENoneTotal time (seconds) the cookie lasts in the client's browser.
    PINAX_REFERRALS_IP_ADDRESS_META_FIELD"HTTP_X_FORWARDED_FOR"The request.META header used to retrieve the respondent's IP address.
    PINAX_REFERRALS_GET_CLIENT_IP_CALLBACK"pinax.referrals.callbacks.get_client_ip"Path to a custom function that takes a request and returns an IP address.
    PINAX_REFERRALS_SECURE_URLSFalseIf True, generated URLs will use https instead of http.
    PINAX_REFERRALS_CODE_GENERATOR_CALLBACK"pinax.referrals.callbacks.generate_code"Path to a callable that generates unique referral codes. Receives (referral_class, referral_instance).
    PINAX_REFERRALS_ACTION_DISPLAY{"RESPONDED": "Clicked on referral link"}A dictionary mapping action codes to user-friendly display text.
    PINAX_REFERRALS_REDIRECT_ATTRIBUTEredirect_toThe URL attribute used to retrieve dynamic redirection destinations.
  4. Use pinax-referrals template tags

    master

    create_referral

    Use this tag to render a form that allows users to generate a referral link. The form is designed for AJAX submission and returns JSON.

    Usage:

    {% load pinax_referrals_tags %}
    
    {# To link to a specific object: #}
    {% create_referral object.get_absolute_url object %}
    
    {# To link to a specific URL: #}
    {% url my_named_url as myurl %}
    {% create_referral myurl %}

    Recommended JavaScript (using jquery.form):

    $(function () {
        $('form.referral').each(function(i, e) {
            var form = $(e);
            var options = {
                dataType: "json",
                success: function(data) {
                    form.html('<input type="text" value="' + data.url + '" />');
                    form.find("input[type=text]").select();
                }
            };
            form.ajaxForm(options);
        });
    });

    referral_responses

    An assignment tag that sets a context variable to a queryset of all responses for all referrals owned by a specific user, ordered by creation date.

    Usage:

    {% load pinax_referrals_tags %}
    {% referral_responses user as responses %}
    
    {% for response in responses %}
        {# response is a ReferralResponse object #}
    {% endfor %}

    action_display filter

    Converts a response action code into user-friendly text based on the PINAX_REFERRALS_ACTION_DISPLAY setting.

    Usage:

    {% load pinax_referrals_tags %}
    <p>{{ response.action|action_display }}</p>
  5. Handle the user_linked_to_response signal

    master

    The user_linked_to_response signal is emitted when a ReferralResponse is successfully linked to a user. You can use this to trigger automatic processes, such as granting special permissions to users who joined via a specific referral action.

    Signal Argument:

    • response: The ReferralResponse object that was just linked.

    Example: Processing a special referral action:

    from pinax.referrals.signals import user_linked_to_response
    from django.dispatch import receiver
    
    @receiver(user_linked_to_response)
    def handle_user_linked_to_response(sender, response, **kwargs):
        if response.action == "SOME_SPECIAL_ACTION":
            # Access the user and the target object
            user = response.user
            target = response.referral.target
            # Perform custom logic (e.g., grant permissions)
            pass
    @receiver(user_linked_to_response)
    def handle_user_linked_to_response(sender, response, **kwargs):
        if response.action == "SOME_SPECIAL_ACTION":
            pass
  6. Retrieve a referral for a request with Referral.referral_for_request

    master

    The Referral.referral_for_request class method retrieves the Referral object associated with the current request. This is useful for implementing custom business logic, such as segmenting permissions or authorizations based on the referral.target.

    referral = Referral.referral_for_request(request)
  7. Record user activity with Referral.record_response

    master

    Use Referral.record_response to track specific actions taken by a user after they have interacted with a referral link. This method checks the current request (user or session) for existing referral responses and records the new action.

    Parameters:

    • request: The current HTTP request.
    • action: A string label for the action being performed.
    • target (optional): A keyword argument to associate the response with a specific object (using a generic foreign key).

    Returns:

    • A ReferralResponse object if a response was recorded.
    • None if the user/session has no previously recorded referral context.

    Example: Recording a specific site action:

    from pinax.referrals.models import Referral
    
    def my_view(request, **kwargs):
        # Records the action 'SOME_ACTION' for the current user/session
        referral_response = Referral.record_response(request, "SOME_ACTION")
        
        # Recording an action associated with a specific object
        referral_response_with_target = Referral.record_response(
            request, 
            "SOME_ACTION", 
            target=some_object
        )
    referral_response = Referral.record_response(request, "SOME_ACTION")
  8. Use Referral.create to generate referral links

    master

    The Referral.create factory method creates a new referral instance. It can be used directly for custom integrations, such as automatically assigning a referral code to a user upon signup.

    Parameters:

    • redirect_to (required): The URL where the user should be redirected.
    • user (optional): The user associated with the referral. If omitted, it is recorded as None.
    • label (optional): A keyword argument to allow users to manage multiple referrals by giving them names.

    Example: Assigning a referral to a user profile via a signal:

    from pinax.referrals.models import Referral
    from django.urls import reverse
    
    # Inside a signal receiver or similar logic
    referral = Referral.create(
        user=profile.user,
        redirect_to=reverse("home")
    )
    profile.referral = referral
    profile.save()

    Template Usage: To display the referral URL in a template:

    {{ user.get_profile.referral.url }}

    Dynamic Redirection: You can append a redirect_to query parameter to the referral URL at runtime to change the destination:

    {{ user.get_profile.referral.url }}?redirect_to=/special/
    referral = Referral.create(
        user=profile.user,
        redirect_to=reverse("home")
    )