### Install pinax-referrals via pip Source: https://github.com/pinax/pinax-referrals/blob/master/README.md Installation command to add pinax-referrals package to your Python environment. This is the first step required to use the referral tracking functionality in your Django project. ```shell pip install pinax-referrals ``` -------------------------------- ### Install and Configure Pinax Referrals in Django Source: https://context7.com/pinax/pinax-referrals/llms.txt Basic installation and configuration steps for Pinax Referrals. Includes adding the app to INSTALLED_APPS, configuring middleware, setting up URLs, and running migrations. Ensure SessionJumpingMiddleware is placed after AuthenticationMiddleware. ```python # Install via pip # pip install pinax-referrals # settings.py INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', # ... other apps 'pinax.referrals', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'pinax.referrals.middleware.SessionJumpingMiddleware', # Must come after AuthenticationMiddleware 'django.contrib.messages.middleware.MessageMiddleware', ] # urls.py from django.urls import path, include urlpatterns = [ # ... other urls path('referrals/', include('pinax.referrals.urls', namespace='pinax_referrals')), ] # Run migrations # python manage.py migrate ``` -------------------------------- ### Create Referral View via AJAX (jQuery and Fetch API) Source: https://context7.com/pinax/pinax-referrals/llms.txt Provides examples of how to create referrals using AJAX. The first snippet uses jQuery's ajaxForm plugin to submit a form and handle the JSON response, which includes the referral URL, code, and updated HTML. The second snippet demonstrates the same functionality using the modern Fetch API. ```javascript # Using the built-in create_referral view via AJAX # This view is automatically available at /referrals/ when URLs are configured # JavaScript (using jQuery) # $(function() { $('form.referral').each(function(i, e) { var form = $(e); var options = { dataType: 'json', success: function(data) { // data.url contains the full referral URL // data.code contains the referral code // data.html contains updated form HTML form.html(''); form.find('input[type=text]').select(); // Or use the code directly console.log('Referral code:', data.code); }, error: function(xhr, status, error) { alert('Error creating referral: ' + error); } }; form.ajaxForm(options); }); }); # Alternative: Modern fetch API document.querySelectorAll('form.referral').forEach(form => { form.addEventListener('submit', async (e) => { e.preventDefault(); const formData = new FormData(form); try { const response = await fetch(form.action, { method: 'POST', body: formData, headers: { 'X-CSRFToken': formData.get('csrfmiddlewaretoken') } }); const data = await response.json(); form.innerHTML = ``; } catch (error) { console.error('Error:', error); } }); }); ``` -------------------------------- ### Configure and Use Custom Code Generator Callback Source: https://context7.com/pinax/pinax-referrals/llms.txt Django settings configuration to use custom referral code generators and example usage showing how the callback is invoked when creating Referral objects. The generated codes appear in the referral's URL structure. ```python # settings.py: PINAX_REFERRALS_CODE_GENERATOR_CALLBACK = 'myapp.callbacks.generate_code' # Usage in code from pinax.referrals.models import Referral referral = Referral.create( user=request.user, redirect_to='/products/' ) # Generated code: ABC-000123 (using custom generator) ``` -------------------------------- ### Django Template Tag for Creating Referral Links Source: https://context7.com/pinax/pinax-referrals/llms.txt This Django template code utilizes the `create_referral` tag to generate referral links. It shows examples for simple URL referrals, referrals associated with a specific object, and includes the default HTML form structure used by the tag. It also shows how to override the default template. ```django {% load pinax_referrals_tags %} {% url 'home' as home_url %} {% create_referral home_url %}

Share this Product

{% create_referral object.get_absolute_url object %}
{% csrf_token %} {% if obj %} {% endif %}
Share & Earn

Get your unique referral link and earn rewards!

{% create_referral request.path %}
``` -------------------------------- ### Handle User Linked to Response Signal Source: https://github.com/pinax/pinax-referrals/blob/master/README.md Receiver function that listens to the `user_linked_to_response` signal to perform automatic processing when users are linked to referral responses. This example demonstrates checking the response action and accessing the user and referral target object for further processing. ```python @receiver(user_linked_to_response) def handle_user_linked_to_response(sender, response, **kwargs): if response.action == "SOME_SPECIAL_ACTION": pass # do something with response.user and response.referral.target (object that referral was linked to) ``` -------------------------------- ### Record User Actions with Pinax Referrals Source: https://context7.com/pinax/pinax-referrals/llms.txt Demonstrates how to record user actions such as purchases or signups using the Referral.record_response method. This function takes the request object, an action label, and an optional target object. It returns a response object if a referral is associated with the request. ```python from pinax.referrals.models import Referral def purchase_view(request): # Record that the user made a purchase response = Referral.record_response(request, 'PURCHASED') if response: # Response was recorded (user came from a referral) print(f"Referral: {response.referral.code}") print(f"Original referrer: {response.referral.user}") print(f"IP: {response.ip_address}") print(f"Session: {response.session_key}") else: # User did not come from a referral print("No referral associated with this user") # ... complete purchase logic return render(request, 'purchase_complete.html') def signup_view(request): if request.method == 'POST': # Create the user account user = create_user_from_form(request.POST) # Record signup action with target object Referral.record_response( request, 'SIGNED_UP', target=user ) # The SessionJumpingMiddleware will automatically link # this response to the user after authentication return redirect('profile_setup') return render(request, 'signup.html') def custom_action_view(request, object_id): obj = MyModel.objects.get(pk=object_id) # Record custom action with specific target Referral.record_response( request, 'CUSTOM_ACTION', target=obj ) return JsonResponse({'status': 'success'}) ``` -------------------------------- ### Create and Manage Referral Objects in Django Source: https://context7.com/pinax/pinax-referrals/llms.txt Demonstrates creating referral objects programmatically using the `Referral.create` method. Covers creating simple, labeled, anonymous, and object-linked referrals. Shows how to access referral properties like URL, code, response count, and creation timestamp. ```python # Creating referrals programmatically from django.urls import reverse from pinax.referrals.models import Referral # Create a simple user referral for the home page referral = Referral.create( user=request.user, redirect_to=reverse('home') ) print(f"Referral URL: {referral.url}") print(f"Referral code: {referral.code}") # Output: https://example.com/referrals/xK9mP2LqR7... # Create a labeled referral for tracking multiple campaigns social_media_referral = Referral.create( user=request.user, redirect_to=reverse('product_detail', kwargs={'pk': 123}), label='twitter_campaign_2024' ) # Create an anonymous referral (no user) for marketing anonymous_referral = Referral.create( redirect_to=reverse('landing_page'), label='email_blast_nov' ) # Create referral linked to a specific object from myapp.models import Product product = Product.objects.get(pk=123) product_referral = Referral.create( user=request.user, redirect_to=reverse('product_detail', kwargs={'pk': product.pk}), target=product, label='product_share' ) # Accessing referral properties print(f"Response count: {referral.response_count}") print(f"Created: {referral.created_at}") print(f"User: {referral.user}") print(f"Target: {referral.target}") # Generic foreign key to any model ``` -------------------------------- ### Process Referral View Source: https://context7.com/pinax/pinax-referrals/llms.txt This is a placeholder description for the process_referral view. This view is automatically available at the URL /referrals// and handles incoming referral clicks by processing the referral code and potentially redirecting the user or applying tracking logic. ```python # The process_referral view handles incoming referral clicks # Available at /referrals// automatically # Example: User clicks on https://example.com/referrals/xK9mP2LqR7.../ ``` -------------------------------- ### Process Referral Signup and Award Bonuses with Signal Receiver Source: https://context7.com/pinax/pinax-referrals/llms.txt Signal receiver that handles user linking to referral responses by awarding points, adding users to groups based on campaign labels, and sending personalized welcome emails. This pattern demonstrates accessing referral metadata and executing business logic on successful conversions. ```python from django.dispatch import receiver from pinax.referrals.signals import user_linked_to_response @receiver(user_linked_to_response) def process_referral_signup(sender, response, **kwargs): """ Handle when a user who clicked a referral link signs up sender: Referral instance response: ReferralResponse instance with user now set """ user = response.user referral = response.referral print(f"User {user.username} linked to referral {referral.code}") print(f"Referrer: {referral.user}") print(f"Action: {response.action}") print(f"Target: {response.target}") # Business logic examples: # Award points/credits if referral.user: referral.user.profile.referral_points += 10 referral.user.profile.save() user.profile.signup_bonus = 10 user.profile.save() # Add to special group if referral.label == 'beta_testers': from django.contrib.auth.models import Group beta_group = Group.objects.get(name='Beta Testers') user.groups.add(beta_group) # Send welcome email with referrer's name if referral.user: send_mail( 'Welcome!', f'Thanks for joining! {referral.user.get_full_name()} recommended us.', 'noreply@example.com', [user.email] ) ``` -------------------------------- ### Advanced Pinax Referrals Settings Source: https://context7.com/pinax/pinax-referrals/llms.txt Optional advanced configuration settings for Pinax Referrals. Allows customization of cookie persistence, secure URL generation, IP address detection, custom callbacks for code generation and response filtering, and action labels. ```python # settings.py - Optional settings for customization # Cookie persistence duration in seconds (None = session-only) PINAX_COOKIE_MAX_AGE = 2592000 # 30 days # Use HTTPS for generated referral URLs PINAX_REFERRALS_SECURE_URLS = True # Custom IP address detection from request headers PINAX_REFERRALS_IP_ADDRESS_META_FIELD = 'HTTP_X_FORWARDED_FOR' # Custom callback for IP extraction (must return string) PINAX_REFERRALS_GET_CLIENT_IP_CALLBACK = 'myapp.utils.get_client_ip' # Custom referral code generator (must return unique string) PINAX_REFERRALS_CODE_GENERATOR_CALLBACK = 'myapp.callbacks.generate_code' # Human-readable action labels for display PINAX_REFERRALS_ACTION_DISPLAY = { 'RESPONDED': 'Clicked on referral link', 'SIGNED_UP': 'Created an account', 'PURCHASED': 'Made a purchase', } # URL parameter name for dynamic redirects PINAX_REFERRALS_REDIRECT_ATTRIBUTE = 'redirect_to' # Custom response filtering callback PINAX_REFERRALS_RESPONSES_FILTER_CALLBACK = 'myapp.callbacks.filter_responses' ``` -------------------------------- ### Configure Django INSTALLED_APPS for pinax-referrals Source: https://github.com/pinax/pinax-referrals/blob/master/README.md Add pinax.referrals to the INSTALLED_APPS setting in your Django settings file. This registers the app with Django and enables its models, migrations, and functionality. ```python INSTALLED_APPS = [ # other apps "pinax.referrals", ] ``` -------------------------------- ### Create a Referral using Referral.create Source: https://github.com/pinax/pinax-referrals/blob/master/README.md The `Referral.create` method is a factory function used to generate new referral objects. It can be called directly or from views. The primary required argument is `redirect_to`, and `user` can be optionally set to `None`. An optional `label` can be provided for managing multiple referrals per user. ```python from pinax.referrals.models import Referral from django.urls import reverse # Example usage within a Django view or signal referral = Referral.create( user=profile.user, redirect_to=reverse("home") ) profile.referral = referral profile.save() ``` -------------------------------- ### Handle Referral Signup with Signal Receiver in Django Source: https://context7.com/pinax/pinax-referrals/llms.txt Django signal receiver that processes new referral signups by granting credits/bonuses to both referred users and referrers, sending notifications, and tracking analytics events. The handler accesses the ReferralResponse object to award benefits based on campaign labels and referral metadata. ```python from django.dispatch import receiver from pinax.referrals.signals import user_linked_to_response @receiver(user_linked_to_response) def handle_new_referral_user(sender, response, **kwargs): """Grant benefits to users who signed up via referral""" user = response.user referrer = response.referral.user # Give referred user a bonus user.profile.add_credits(100) # Give referrer a reward if referrer: referrer.profile.add_credits(50) # Send notification send_notification( referrer, f"{user.username} signed up using your referral!" ) # Check if referral was for specific campaign if response.referral.label == 'premium_campaign': user.profile.grant_premium_trial(days=30) # Track in analytics track_event('referral_conversion', { 'referrer_id': referrer.id if referrer else None, 'new_user_id': user.id, 'campaign': response.referral.label }) ``` -------------------------------- ### Django View for Referral Landing Page Source: https://context7.com/pinax/pinax-referrals/llms.txt This Python function handles the landing page logic for referred users. It checks for a referral using `Referral.referral_for_request`, sets a context variable to indicate if the user came from a referral, and optionally displays the referrer's name. It then renders a 'landing.html' template. ```python from django.shortcuts import render def landing_page(request): referral = Referral.referral_for_request(request) context = { 'show_special_offer': referral is not None, 'referrer_name': referral.user.get_full_name() if referral and referral.user else None } return render(request, 'landing.html', context) ``` -------------------------------- ### Track Referral Metrics and A/B Test Conversions with Signal Receiver Source: https://context7.com/pinax/pinax-referrals/llms.txt Signal receiver that logs referral conversion statistics and triggers A/B test tracking when a referred user completes signup. Creates ReferralStats records and conditionally invokes A/B testing functions based on referral label patterns. ```python @receiver(user_linked_to_response) def track_referral_metrics(sender, response, **kwargs): """Track successful referral conversions""" referral = response.referral # Update referral statistics ReferralStats.objects.create( referral=referral, converted_user=response.user, conversion_date=timezone.now(), source_action=response.action ) # Trigger A/B test tracking if referral.label.startswith('ab_test_'): track_ab_test_conversion(referral.label, response.user) ``` -------------------------------- ### Configure Django MIDDLEWARE for SessionJumpingMiddleware Source: https://github.com/pinax/pinax-referrals/blob/master/README.md Add SessionJumpingMiddleware to your Django MIDDLEWARE setting after AuthenticationMiddleware. This middleware links users who register and authenticate after clicking a referral link to the original referrer. ```python MIDDLEWARE = [ # other middleware "django.contrib.auth.middleware.AuthenticationMiddleware", "pinax.referrals.middleware.SessionJumpingMiddleware", ] ``` -------------------------------- ### Django Custom View Integration with Referral Tracking Source: https://context7.com/pinax/pinax-referrals/llms.txt This Python code demonstrates integrating referral tracking into a custom Django `DetailView`. It overrides `get_context_data` to check for referrals and record 'VIEWED_PRODUCT' responses. The `post` method is overridden to record 'ADDED_TO_CART' actions. ```python from django.views.generic import DetailView from pinax.referrals.models import Referral from django.http import JsonResponse class ProductDetailView(DetailView): model = Product template_name = 'product_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) referral = Referral.referral_for_request(self.request) context['referral'] = referral if referral: Referral.record_response( self.request, 'VIEWED_PRODUCT', target=self.object ) return context def post(self, request, *args, **kwargs): self.object = self.get_object() Referral.record_response(request, 'ADDED_TO_CART', target=self.object) return JsonResponse({'status': 'success'}) ``` -------------------------------- ### Create Referrals Database Migrations Source: https://github.com/pinax/pinax-referrals/blob/master/README.md Django management command to generate database migrations for the referrals application. Necessary when using custom user models or upgrading Django versions to ensure database schema consistency. ```shell $ python manage.py makemigrations referrals ``` -------------------------------- ### Configure Django URL routing for pinax-referrals Source: https://github.com/pinax/pinax-referrals/blob/master/README.md Include pinax.referrals.urls in your Django URL configuration with the namespace 'pinax_referrals'. This sets up the referral link handling endpoints at the /referrals/ path. ```python urlpatterns = [ # other urls url(r"^referrals/", include("pinax.referrals.urls", namespace="pinax_referrals")), ] ``` -------------------------------- ### Retrieve Referral Information Source: https://context7.com/pinax/pinax-referrals/llms.txt Shows how to retrieve referral data associated with the current request using Referral.referral_for_request or by querying all responses for a user's referrals. This can be used to apply custom business logic or display referral statistics. ```python # Get the referral object for the current request from pinax.referrals.models import Referral def my_view(request): referral = Referral.referral_for_request(request) if referral: # User came from a referral link print(f"Referral code: {referral.code}") print(f"Referrer: {referral.user}") print(f"Target object: {referral.target}") print(f"Label: {referral.label}") # Apply custom business logic if referral.label == 'premium_campaign': # Give user premium trial request.user.grant_premium_trial() return render(request, 'page.html', {'referral': referral}) # Get all responses for a user's referrals def referral_dashboard(request): user_referrals = Referral.objects.filter(user=request.user) for referral in user_referrals: print(f"Referral: {referral.label}") print(f"Total clicks: {referral.response_count}") # Get all responses using filtered callback responses = referral.filtered_responses() for response in responses: print(f" Action: {response.action}") print(f" User: {response.user}") print(f" Date: {response.created_at}") return render(request, 'dashboard.html', { 'referrals': user_referrals }) ``` -------------------------------- ### Database Migration - Add Referral Label Column Source: https://github.com/pinax/pinax-referrals/blob/master/README.md SQL migration for version 0.5 that adds the ability to label referrals. This migration adds a new varchar column to the anafero_referral table with a default empty string value to support referral labeling functionality. ```sql ALTER TABLE "anafero_referral" ADD COLUMN "label" varchar(100) NOT NULL DEFAULT ''; ``` -------------------------------- ### Link Anonymous to Logged-in Users with Django Middleware Source: https://context7.com/pinax/pinax-referrals/llms.txt The `SessionJumpingMiddleware` automatically associates referral responses made by anonymous users with their account once they log in. It relies on a cookie set when a user clicks a referral link. Ensure this middleware is placed after `AuthenticationMiddleware` in `settings.py`. ```python # The middleware automatically links anonymous referral responses to users after login # Configuration in settings.py (must come after AuthenticationMiddleware) MIDDLEWARE = [ 'django.contrib.auth.middleware.AuthenticationMiddleware', 'pinax.referrals.middleware.SessionJumpingMiddleware', ] # How it works: # 1. User clicks referral link while anonymous # - Cookie set: pinax-referral=xK9mP2LqR7...:session_key_abc123 # - Response recorded with session_key but no user # # 2. User signs up and logs in # - Middleware detects authenticated user + cookie # - Links all responses with session_key_abc123 to the new user # - Deletes the cookie # - Fires user_linked_to_response signal for each response ``` -------------------------------- ### Display Referral Responses using Django Tag Source: https://context7.com/pinax/pinax-referrals/llms.txt The `referral_responses` template tag displays a list of referral responses associated with a user. It can be used to populate tables or activity feeds. Dependencies include the `pinax_referrals_tags` library. It takes a user object as input and outputs a list of response objects. ```django {% load pinax_referrals_tags %} {% referral_responses user as responses %}

Referral Activity

{% if responses %} {% for response in responses %} {% endfor %}
Date Action User Referral Code
{{ response.created_at|date:"M d, Y H:i" }} {{ response.action|action_display }} {% if response.user %} {{ response.user.username }} {% else %} Anonymous ({{ response.session_key|truncatechars:10 }}) {% endif %} {{ response.referral.code }} {% if response.referral.label %} {{ response.referral.label }} {% endif %}
{% else %}

No referral activity yet.

{% endif %}
{% referral_responses user as all_responses %}
{% for response in all_responses|slice:":10" %}
{{ response.action|action_display }} {{ response.created_at|timesince }} ago {% if response.target %}
Target: {{ response.target }} {% endif %}
{% endfor %}
``` -------------------------------- ### Referral Template Context Variables Source: https://github.com/pinax/pinax-referrals/blob/master/README.md Context dictionary passed to the `_create_referral_form.html` template containing the referral URL, associated object, and its content type. Used when rendering referral creation forms with object context. ```python { "url": url, "obj": obj, "obj_ct": ContentType.objects.get_for_model(obj) } ``` -------------------------------- ### Database Migration - Add Target Content Type and Object ID Source: https://github.com/pinax/pinax-referrals/blob/master/README.md SQL migration for version 0.9 that adds the ability to record a specific object in reference to each referral response. This migration adds two new columns to the anafero_referralresponse table to support content type and object ID foreign key relationships. ```sql ALTER TABLE "anafero_referralresponse" ADD COLUMN "target_content_type_id" integer REFERENCES "django_content_type" ("id") DEFERRABLE INITIALLY DEFERRED, ADD COLUMN "target_object_id" integer; ``` -------------------------------- ### Record a Referral Response using Referral.record_response Source: https://github.com/pinax/pinax-referrals/blob/master/README.md The `Referral.record_response` class method tracks user interactions with referral links. It checks for existing referral responses associated with the current request's user or session and records the specified action. It can also associate the response with a specific target object using the `target` keyword argument. ```python from pinax.referrals.models import Referral def my_view(request, **kwargs): # other code referral_response = Referral.record_response(request, "SOME_ACTION") # Example with a target object # referral_response = Referral.record_response(request, "SOME_ACTION", target=some_object) return # your response ``` -------------------------------- ### Create Referral Template Tag with Object Source: https://github.com/pinax/pinax-referrals/blob/master/README.md Django template tag implementation for rendering a referral creation form linked to a specific object. The object parameter is optional and can be omitted if only recording referrals to a URL. ```django {% load pinax_referrals_tags %} {% create_referral object.get_absolute_url object %} ``` -------------------------------- ### Render Referral URL in Django Templates Source: https://github.com/pinax/pinax-referrals/blob/master/README.md Referral URLs can be dynamically rendered in Django templates. Users can forward this URL to others. The `redirect_to` parameter can be appended to the URL at runtime to specify an alternative destination, which can be configured via Django settings. ```django {{ user.get_profile.referral.url }} {{ user.get_profile.referral.url }}?redirect_to=/special/ ``` -------------------------------- ### Referral Responses Assignment Template Tag Source: https://github.com/pinax/pinax-referrals/blob/master/README.md Django assignment tag that retrieves all referral responses for a given user, ordered by creation date. Useful for displaying referral activity and tracking performance of different referral links. ```django {% load pinax_referrals_tags %} {% referral_responses user as responses %} {% for response in responses %} {# response is a ReferralResponse object #} {% endfor %} ``` -------------------------------- ### Format Referral Actions using Django Filter Source: https://context7.com/pinax/pinax-referrals/llms.txt The `action_display` template filter converts raw action codes (e.g., 'RESPONDED') into human-readable strings (e.g., 'Clicked on referral link'). This can be customized via `PINAX_REFERRALS_ACTION_DISPLAY` in `settings.py`. It's used within loops iterating over referral responses. ```django {% load pinax_referrals_tags %} {% referral_responses user as responses %} {% for response in responses %}

{{ response.action|action_display }}

{% endfor %}

My Referrals

{% referral_responses user as responses %}

{{ responses|length }}

Total Responses

    {% for response in responses %}
  • {{ response.action|action_display }} {% if response.user %}
    by {{ response.user.username }} {% endif %}
    {{ response.created_at|timesince }} ago
  • {% endfor %}
``` -------------------------------- ### Generate Sequential Referral Codes with Prefix Source: https://context7.com/pinax/pinax-referrals/llms.txt Custom callback that generates sequential referral codes with user-based or default prefixes in the format PREFIX-XXXXXX. Retrieves the last referral ID from the database to ensure sequential numbering and supports different prefixes for authenticated versus anonymous referrals. ```python def generate_sequential_code(referral_class, referral): """Generate codes like REF-001234""" last_referral = referral_class.objects.order_by('-id').first() next_id = (last_referral.id + 1) if last_referral else 1 if referral.user: prefix = referral.user.username[:3].upper() else: prefix = 'REF' return f"{prefix}-{next_id:06d}" ``` -------------------------------- ### Custom Referral Code Generation Callback Source: https://github.com/pinax/pinax-referrals/blob/master/README.md The `PINAX_REFERRALS_CODE_GENERATOR_CALLBACK` setting allows customization of how referral codes are generated. You can provide a path to a custom function that takes the referral class and instance as arguments. The generated code must be unique to avoid conflicts. ```python # Example custom callback function def generate_code(referral_class, referral): return referral.user.username # In settings.py: # PINAX_REFERRALS_CODE_GENERATOR_CALLBACK = "your_app.utils.generate_code" ``` -------------------------------- ### Action Display Filter Template Tag Source: https://github.com/pinax/pinax-referrals/blob/master/README.md Django template filter that converts response action codes into user-friendly display strings based on the `PINAX_REFERRALS_ACTION_DISPLAY` setting. Provides readable output for referral response actions. ```django {% load pinax_referrals_tags %}

{{ response.action|action_display }}

``` -------------------------------- ### Create Referral Template Tag with URL Only Source: https://github.com/pinax/pinax-referrals/blob/master/README.md Django template tag for generating a referral link to a URL without associating it to a specific object. Useful for recording referrals to general pages or named URL patterns. ```django {% load pinax_referrals_tags %} {% url my_named_url as myurl %} {% create_referral myurl %} ``` -------------------------------- ### Generate Custom Referral Codes with Username-Based Hashing Source: https://context7.com/pinax/pinax-referrals/llms.txt Custom callback function that generates unique referral codes based on user information and timestamps, using SHA-256 hashing for authenticated users and secure random tokens for anonymous referrals. Must be configured in Django settings via PINAX_REFERRALS_CODE_GENERATOR_CALLBACK. ```python import hashlib from django.utils import timezone def generate_code(referral_class, referral): """ Generate custom referral codes based on user information Must return a unique string """ if referral.user: # Use username-based codes for users base = f"{referral.user.username}_{timezone.now().timestamp()}" code = hashlib.sha256(base.encode()).hexdigest()[:12].upper() # Ensure uniqueness while referral_class.objects.filter(code=code).exists(): base = f"{base}_{random.randint(1000, 9999)}" code = hashlib.sha256(base.encode()).hexdigest()[:12].upper() return code else: # Random codes for anonymous referrals return secrets.token_urlsafe(16) ``` -------------------------------- ### Filter Referral Responses (Django Python) Source: https://context7.com/pinax/pinax-referrals/llms.txt Custom filtering logic for ReferralResponse objects in Django. It supports filtering by user and referral, excludes bot/spam responses based on blocked IPs, and limits results to the last 90 days. It also includes prefetching and selecting related objects for performance. ```python from pinax.referrals.models import ReferralResponse from django.db.models import Q, Count from django.utils import timezone from datetime import timedelta def filter_responses(user=None, referral=None): """ Custom filtering logic for referral responses Returns a queryset of ReferralResponse objects """ responses = ReferralResponse.objects.select_related( 'referral', 'user' ).prefetch_related( 'target_content_type' ) if user: # Get responses for all referrals owned by this user responses = responses.filter(referral__user=user) # Exclude bot/spam responses responses = responses.exclude( ip_address__in=get_blocked_ips() ) if referral: responses = responses.filter(referral=referral) # Only show responses from last 90 days cutoff_date = timezone.now() - timedelta(days=90) responses = responses.filter(created_at__gte=cutoff_date) # Order by most recent return responses.order_by('-created_at') ``` -------------------------------- ### Handle Referral Form AJAX Submission with jQuery Source: https://github.com/pinax/pinax-referrals/blob/master/README.md JavaScript implementation using jquery.form plugin to handle AJAX submission of referral forms. Captures the response JSON containing the generated referral URL and displays it in a text input field. ```javascript $(function () { $('form.referral').each(function(i, e) { var form = $(e); options = { dataType: "json", success: function(data) { form.html(''); form.find("input[type=text]").select(); } } form.ajaxForm(options); }); }); ``` -------------------------------- ### Advanced Client IP Extraction with Multiple Headers (Django Python) Source: https://context7.com/pinax/pinax-referrals/llms.txt An advanced IP address extraction function that attempts to retrieve the client's IP from multiple common headers (X-Forwarded-For, X-Real-IP, CF-Connecting-IP) before falling back to REMOTE_ADDR. It includes IP address validation. ```python # Alternative: Support multiple header options def get_client_ip_advanced(request): """Try multiple headers for IP detection""" headers_to_check = [ 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CF_CONNECTING_IP', # Cloudflare 'REMOTE_ADDR' ] for header in headers_to_check: ip = request.META.get(header, '').split(',')[0].strip() if ip and is_valid_ip(ip): return ip return '0.0.0.0' def is_valid_ip(ip): """Validate IP address format""" import ipaddress try: ipaddress.ip_address(ip) return True except ValueError: return False ``` -------------------------------- ### Retrieve Referral for Request using Referral.referral_for_request Source: https://github.com/pinax/pinax-referrals/blob/master/README.md 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 comparing referral targets with other objects for permission or authorization checks, enabling more granular control over the referral system. ```python from pinax.referrals.models import Referral # Inside a view or other request-aware context referral = Referral.referral_for_request(request) ``` -------------------------------- ### Extract Client IP Address from Request (Django Python) Source: https://context7.com/pinax/pinax-referrals/llms.txt Provides a custom callback function to extract the client's IP address from an incoming Django request. It handles common proxy headers like X-Forwarded-For and falls back to REMOTE_ADDR. ```python # Custom IP address extraction # settings.py: PINAX_REFERRALS_GET_CLIENT_IP_CALLBACK = 'myapp.callbacks.get_client_ip' # myapp/callbacks.py def get_client_ip(request): """ Extract client IP address from request Handles various proxy configurations """ # Check X-Forwarded-For header (for proxies/load balancers) x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: # Take the first IP in the chain ip = x_forwarded_for.split(',')[0].strip() else: # Fallback to REMOTE_ADDR ip = request.META.get('REMOTE_ADDR', '') return ip ``` -------------------------------- ### Filter Responses with Aggregated Stats (Django Python) Source: https://context7.com/pinax/pinax-referrals/llms.txt Enhances referral response filtering by adding aggregated statistics like response count and latest activity date. This function uses Django's ORM for annotation and aggregation, providing deeper insights into referral performance. ```python def filter_responses_with_stats(user=None, referral=None): """Filter responses and add aggregated statistics""" from django.db.models import Count, Max responses = ReferralResponse.objects.all() if user: responses = responses.filter(referral__user=user) if referral: responses = responses.filter(referral=referral) # Annotate with additional stats responses = responses.annotate( response_count=Count('referral__responses'), latest_activity=Max('created_at') ) return responses.order_by('-created_at') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.