### Install django-lazysignup using pip Source: https://github.com/danfairs/django-lazysignup/blob/master/docs/install.rst This command installs the django-lazysignup package from PyPI using pip. Ensure you have pip installed and accessible in your environment. ```bash pip install django-lazysignup ``` -------------------------------- ### Installation and Configuration for django-lazysignup Source: https://context7.com/danfairs/django-lazysignup/llms.txt Configure django-lazysignup in your Django settings and URL configuration to enable lazy user functionality. This involves adding the app to INSTALLED_APPS, including the LazySignupBackend in AUTHENTICATION_BACKENDS, and including the lazysignup URLs. ```python # settings.py INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', # ... other apps 'lazysignup', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'lazysignup.backends.LazySignupBackend', ) # Optional: Custom user model (defaults to AUTH_USER_MODEL) # LAZYSIGNUP_USER_MODEL = 'myapp.CustomUser' # Optional: Custom form for account conversion # LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = 'myproject.forms.MyUserCreationForm' # Optional: Enable/disable lazy signup (default: True) # LAZYSIGNUP_ENABLE = True # Optional: Custom user agent blacklist (replaces defaults) # LAZYSIGNUP_USER_AGENT_BLACKLIST = ['slurp', 'googlebot', 'yandex', 'msnbot', 'baiduspider'] # urls.py from django.urls import path, include urlpatterns = [ # ... other urls path('convert/', include('lazysignup.urls')) ] ``` -------------------------------- ### Example Custom User Model with UserManager (Django) Source: https://github.com/danfairs/django-lazysignup/blob/master/docs/user.rst An example of a custom Django User model that subclasses AbstractUser and uses Django's UserManager. This demonstrates how to ensure your custom user model is compatible with lazysignup's requirements, including the presence of a `create_user` method on the manager and the ability to fetch users by primary key and username. ```python from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class MyCustomUser(AbstractUser): objects = UserManager() notes = models.TextField(blank=True, null=True) ``` -------------------------------- ### Configure and Customize LazySignup Convert View Source: https://context7.com/danfairs/django-lazysignup/llms.txt This snippet shows how to configure the built-in Django LazySignup convert view in your `urls.py`. It demonstrates setting custom templates for both regular and AJAX requests, specifying a redirect field name, and defining an anonymous redirect URL. The example also includes a basic HTML template for the conversion form and a JavaScript snippet for AJAX conversion. ```python # Customizing the convert view in your urls.py from django.urls import path from lazysignup.views import convert urlpatterns = [ path('signup/', convert, { 'template_name': 'myapp/custom_convert.html', 'ajax_template_name': 'myapp/custom_convert_ajax.html', 'redirect_field_name': 'next', 'anonymous_redirect': '/login/', }, name='lazysignup_convert'), ] ``` ```html # Custom convert template (lazysignup/convert.html) """ {% extends "base.html" %} {% block content %}

Create Your Account

{% csrf_token %} {{ form.as_p }}
{% endblock %} """ ``` ```javascript # AJAX conversion example (JavaScript) """ fetch('/convert/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': getCookie('csrftoken') }, body: 'username=newuser&password1=securepass123&password2=securepass123' }) .then(response => { if (response.ok) { console.log('Account created successfully!'); window.location.reload(); } else { response.text().then(errors => console.log('Errors:', errors)); } }); """ ``` -------------------------------- ### Convert View and URL Configuration Source: https://context7.com/danfairs/django-lazysignup/llms.txt The built-in `convert` view handles the process of converting lazy users. It can be included directly via `lazysignup.urls` or customized with specific templates and redirect behaviors. ```APIDOC ## Convert View ### Description Provides a built-in view for converting lazy users to permanent accounts. It can be configured with custom templates and redirect URLs. ### Method `GET`, `POST` ### Endpoint - Default: `/convert/` (when included via `lazysignup.urls`) - Custom: Configurable in your `urls.py` ### Parameters #### Path Parameters None #### Query Parameters - **redirect_to** (string) - Optional - The URL to redirect to after successful conversion. #### Request Body (for POST requests) - **username** (string) - Required - The desired username for the permanent account. - **password1** (string) - Required - The desired password for the permanent account. - **password2** (string) - Required - Password confirmation. - Other fields defined by the `UserCreationForm` or custom form. ### Request Example (AJAX) ```javascript fetch('/convert/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken': getCookie('csrftoken') }, body: 'username=newuser&password1=securepass123&password2=securepass123' }) .then(response => { if (response.ok) { console.log('Account created successfully!'); window.location.reload(); } else { response.text().then(errors => console.log('Errors:', errors)); } }); ``` ### Response #### Success Response (200 or redirect) - If AJAX request: JSON response with success message or user data. - If regular request: Redirect to the `done_url` or the `redirect_to` parameter. #### Response Example (AJAX Success) ```json { "status": "success", "message": "User converted successfully." } ``` #### Error Response - **400 Bad Request**: If the form is invalid. Returns form errors. - **403 Forbidden**: If the user is not a lazy user. ### URL Configuration Example ```python # urls.py from django.urls import path from lazysignup.views import convert urlpatterns = [ path('signup/', convert, { 'template_name': 'myapp/custom_convert.html', 'ajax_template_name': 'myapp/custom_convert_ajax.html', 'redirect_field_name': 'next', 'anonymous_redirect': '/login/', }, name='lazysignup_convert'), ] ``` ``` -------------------------------- ### Custom User Model Support for Django LazySignup Source: https://context7.com/danfairs/django-lazysignup/llms.txt Demonstrates how to configure django-lazysignup to work with a custom Django User model. Includes defining the custom user model, setting AUTH_USER_MODEL, and using the @allow_lazy_user decorator. ```python # models.py - Custom User Model from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class CustomUser(AbstractUser): """Custom user model with additional fields.""" objects = UserManager() # Required: must have create_user method phone = models.CharField(max_length=20, blank=True) avatar = models.ImageField(upload_to='avatars/', blank=True, null=True) @classmethod def generate_username(cls): """ Optional: Custom username generation for lazy users. If not defined, lazysignup uses UUID-based usernames. """ import uuid return f"guest_{uuid.uuid4().hex[:8]}" # settings.py AUTH_USER_MODEL = 'myapp.CustomUser' # LAZYSIGNUP_USER_MODEL defaults to AUTH_USER_MODEL # Only set this if you want lazy users to use a different model # LAZYSIGNUP_USER_MODEL = 'myapp.CustomUser' # Usage remains the same from lazysignup.decorators import allow_lazy_user from django.http import HttpResponse @allow_lazy_user def my_view(request): # request.user is now a CustomUser instance print(request.user.phone) # Access custom fields return HttpResponse('OK') ``` -------------------------------- ### Configure Django AUTHENTICATION_BACKENDS Source: https://github.com/danfairs/django-lazysignup/blob/master/docs/install.rst This configuration snippet adds the LazySignupBackend to your Django project's authentication backends. It requires django.contrib.auth.backends.ModelBackend to be present as well. ```python AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'lazysignup.backends.LazySignupBackend', ) ``` -------------------------------- ### Convert Lazy User to Permanent Account with LazyUser.objects.convert() Source: https://context7.com/danfairs/django-lazysignup/llms.txt This Python code demonstrates how to convert a lazy user to a permanent user account using the `LazyUser.objects.convert()` method. It takes a Django form instance as input and handles potential `NotLazyError` exceptions. The conversion process saves the form, deletes the lazy user record, and sends a 'converted' signal. ```python from lazysignup.models import LazyUser from lazysignup.forms import UserCreationForm from lazysignup.exceptions import NotLazyError def convert_lazy_user(request): """Convert a lazy user to a permanent account.""" if request.method == 'POST': # Create form bound to the current lazy user form = UserCreationForm(request.POST, instance=request.user) if form.is_valid(): try: # Convert the user - this will: # 1. Save the form (set username/password) # 2. Delete the LazyUser record # 3. Send the 'converted' signal converted_user = LazyUser.objects.convert(form) print(f"User converted successfully: {converted_user.username}") print(f"User can now login with password: {converted_user.has_usable_password()}") # True return converted_user except NotLazyError: # User was already converted or was never a lazy user print("Cannot convert: user is not a lazy user") return None else: print(f"Form errors: {form.errors}") return None ``` -------------------------------- ### Manage Temporary Users with LazyUser Model and Manager Source: https://context7.com/danfairs/django-lazysignup/llms.txt The LazyUser model and its manager provide functionality to create, track, and query temporary user accounts. The `create_lazy_user()` method generates a new temporary user, and the manager allows filtering lazy users by creation date or retrieving the appropriate user model. ```python from lazysignup.models import LazyUser from django.contrib.auth import get_user_model User = get_user_model() # Create a new lazy user programmatically user, username = LazyUser.objects.create_lazy_user() print(f"Created lazy user: {username}") print(f"User ID: {user.id}") print(f"Has usable password: {user.has_usable_password()}") # False # Check if a LazyUser record exists for a user lazy_record = LazyUser.objects.filter(user=user).first() if lazy_record: print(f"Lazy user created at: {lazy_record.created}") # Get the user class being used (respects LAZYSIGNUP_USER_MODEL setting) user_class = LazyUser.get_user_class() print(f"User model: {user_class}") # Query lazy users by creation date from datetime import datetime, timedelta old_lazy_users = LazyUser.objects.filter( created__lt=datetime.now() - timedelta(days=30) ) print(f"Found {old_lazy_users.count()} lazy users older than 30 days") ``` -------------------------------- ### Handle User Conversion Signal in Django Source: https://context7.com/danfairs/django-lazysignup/llms.txt Listen for the 'converted' signal to execute custom logic when a lazy user is successfully converted to a permanent account. This involves defining receiver functions that accept sender and user objects, and can perform actions like sending emails or creating user profiles. Dependencies include Django's signal framework and potentially other Django apps. ```python from django.dispatch import receiver from lazysignup.signals import converted @receiver(converted) def on_user_converted(sender, user, **kwargs): """ Handle user conversion - triggered after LazyUser.objects.convert() succeeds. Args: sender: The LazyUserManager instance user: The newly converted User object """ print(f"User {user.username} has been converted!") # Example: Send welcome email from django.core.mail import send_mail send_mail( subject='Welcome to Our Site!', message=f'Hi {user.username}, thanks for creating your account!', from_email='noreply@example.com', recipient_list=[user.email], fail_silently=True, ) # Example: Create user profile from myapp.models import UserProfile UserProfile.objects.get_or_create( user=user, defaults={'converted_from_lazy': True} ) # Example: Log the conversion import logging logger = logging.getLogger(__name__) logger.info(f"Lazy user converted: {user.id} -> {user.username}") @receiver(converted) def transfer_temporary_data(sender, user, **kwargs): """Transfer any temporary data to permanent storage on conversion.""" # Example: Move shopping cart from session to database # Example: Save temporary preferences to user profile pass ``` -------------------------------- ### Listen for the Converted User Signal in Django Source: https://github.com/danfairs/django-lazysignup/blob/master/docs/usage.rst The 'converted' signal is sent when a temporary user account is converted to a real user account. You can listen for this signal to perform custom actions, such as logging or further processing of the new user object. ```python from lazysignup.signals import converted from django.dispatch import receiver @receiver(converted) def my_callback(sender, **kwargs): print "New user account: %s!" % kwargs['user'].username ``` -------------------------------- ### Configure Django LazySignup Authentication Backend Source: https://context7.com/danfairs/django-lazysignup/llms.txt Integrate the LazySignupBackend into your Django project's AUTHENTICATION_BACKENDS setting to enable authentication for lazy users. This backend allows users to be authenticated by username without a password, typically used internally during lazy user creation. It also annotates authenticated users with the backend path for easy identification. ```python # The backend is configured in settings.py: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'lazysignup.backends.LazySignupBackend', ) # The backend authenticates users by username only (no password) # This is used internally when creating lazy users from django.contrib.auth import authenticate # Internal usage (you typically don't call this directly) from lazysignup.models import LazyUser user, username = LazyUser.objects.create_lazy_user() authenticated_user = authenticate(username=username) # Uses LazySignupBackend # The backend also annotates users with the backend path for is_lazy_user detection print(authenticated_user.backend) # 'lazysignup.backends.LazySignupBackend' ``` -------------------------------- ### Include lazysignup URLs in Django URLConf Source: https://github.com/danfairs/django-lazysignup/blob/master/docs/install.rst This code snippet integrates lazysignup's URL patterns into your project's main URL configuration. It assumes you have a urlpatterns variable defined and are using Django's include function. ```python from django.conf.urls import url, include urlpatterns += ( url(r'^convert/', include('lazysignup.urls')), ) ``` -------------------------------- ### LazyUser.objects.convert() Method Source: https://context7.com/danfairs/django-lazysignup/llms.txt This method converts a lazy user account into a permanent one by saving the provided form instance. It handles the deletion of the LazyUser record and triggers a 'converted' signal upon success. ```APIDOC ## LazyUser.objects.convert() ### Description Converts a lazy user to a permanent user account using a form instance. ### Method `convert(form_instance)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (operates on a form instance) ### Request Example ```python from lazysignup.models import LazyUser from lazysignup.forms import UserCreationForm from lazysignup.exceptions import NotLazyError def convert_lazy_user(request): if request.method == 'POST': form = UserCreationForm(request.POST, instance=request.user) if form.is_valid(): try: converted_user = LazyUser.objects.convert(form) print(f"User converted successfully: {converted_user.username}") return converted_user except NotLazyError: print("Cannot convert: user is not a lazy user") return None else: print(f"Form errors: {form.errors}") return None ``` ### Response #### Success Response (200) - **converted_user** (User object) - The newly created permanent user object. #### Response Example ```json { "username": "converted_user", "email": "user@example.com" } ``` #### Error Response - **NotLazyError**: Raised if the user is not a lazy user or has already been converted. ``` -------------------------------- ### Extend LazySignup User Creation Form with Custom Fields Source: https://context7.com/danfairs/django-lazysignup/llms.txt This Python code defines a custom user creation form that extends the base `UserCreationForm` from `lazysignup`. It adds fields like `email`, `first_name`, `last_name`, and `newsletter`. The `save` method is overridden to handle these additional fields and includes logic for newsletter subscription. The `get_credentials` method is also provided for re-authentication. To use this custom form, set `LAZYSIGNUP_CUSTOM_USER_CREATION_FORM` in your `settings.py`. ```python from django import forms from django.contrib.auth import get_user_model from lazysignup.forms import UserCreationForm as BaseUserCreationForm User = get_user_model() class CustomUserCreationForm(BaseUserCreationForm): """Extended form with additional fields for account conversion.""" email = forms.EmailField(required=True) first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) newsletter = forms.BooleanField(required=False, label="Subscribe to newsletter") class Meta(BaseUserCreationForm.Meta): model = User fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2') def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() # Handle newsletter subscription if self.cleaned_data.get('newsletter'): # Subscribe user to newsletter pass return user def get_credentials(self): """Return credentials for re-authentication after conversion.""" return { 'username': self.cleaned_data['username'], 'password': self.cleaned_data['password1'] } # settings.py LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = 'myapp.forms.CustomUserCreationForm' ``` -------------------------------- ### Require Lazy User and Require Non-Lazy User Decorators (Python) Source: https://github.com/danfairs/django-lazysignup/blob/master/docs/usage.rst These decorators control access to views based on user type. `require_lazy_user` ensures only temporary users can access the view, while `require_nonlazy_user` ensures only regular users can. Both can accept arguments for redirection. ```python # Example usage (not directly provided in text, but implied functionality) # from lazysignup.decorators import require_lazy_user, require_nonlazy_user # @require_lazy_user # def lazy_only_view(request): # pass # # @require_nonlazy_user # def non_lazy_only_view(request): # pass ``` -------------------------------- ### Custom LazyUser Admin Configuration in Django Source: https://context7.com/danfairs/django-lazysignup/llms.txt Configures the Django admin interface for the LazyUser model. It defines display fields, filters, search options, date hierarchy, and custom actions for managing lazy users. ```python from django.contrib import admin from lazysignup.models import LazyUser @admin.register(LazyUser) class CustomLazyUserAdmin(admin.ModelAdmin): list_display = ('user', 'created', 'get_email', 'days_since_created') list_filter = ('created',) search_fields = ('user__username', 'user__email') date_hierarchy = 'created' actions = ('cleanup_lazyusers', 'send_conversion_reminder') def get_email(self, obj): return obj.user.email or 'No email' get_email.short_description = 'Email' def days_since_created(self, obj): from django.utils import timezone delta = timezone.now() - obj.created return delta.days days_since_created.short_description = 'Age (days)' def send_conversion_reminder(self, request, queryset): """Send email reminders to lazy users to convert their accounts.""" count = 0 for lazy_user in queryset: if lazy_user.user.email: # Send reminder email count += 1 self.message_user(request, f"Sent {count} reminder emails") send_conversion_reminder.short_description = "Send conversion reminder email" ``` -------------------------------- ### User Agent Blacklist Setting (Django Settings) Source: https://github.com/danfairs/django-lazysignup/blob/master/docs/usage.rst The `USER_AGENT_BLACKLIST` setting in Django's settings.py allows you to specify regular expressions for user agent strings. Requests matching any of these regexes will prevent the creation of temporary user accounts, helping to avoid bots. If not specified, a default list is used. ```python # Example setting in settings.py # USER_AGENT_BLACKLIST = [ # r'googlebot', # r'slurp', # ] ``` -------------------------------- ### Custom User Creation Form Source: https://context7.com/danfairs/django-lazysignup/llms.txt Allows you to extend the default `UserCreationForm` to include additional fields for collecting user data during the conversion process. This custom form must be specified in your Django settings. ```APIDOC ## Custom User Creation Form ### Description Defines a custom form that extends `lazysignup.forms.UserCreationForm` to include additional fields and custom save logic for user account conversion. ### Method Inherits from `lazysignup.forms.UserCreationForm` ### Endpoint Not applicable (this is a form definition). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **username** (string) - Required - The desired username. - **email** (string) - Required - The user's email address. - **first_name** (string) - Optional - The user's first name. - **last_name** (string) - Optional - The user's last name. - **password1** (string) - Required - The desired password. - **password2** (string) - Required - Password confirmation. - **newsletter** (boolean) - Optional - A custom field to indicate newsletter subscription. ### Request Example (See Convert View Request Example - the body would include fields from this custom form) ### Response #### Success Response (200) - **user** (User object) - The saved user object, potentially with additional attributes set by the custom form's `save` method. #### Response Example ```json { "username": "customuser", "email": "custom@example.com", "first_name": "John", "last_name": "Doe" } ``` ### Settings Configuration To use a custom form, set the `LAZYSIGNUP_CUSTOM_USER_CREATION_FORM` setting in your `settings.py`: ```python # settings.py LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = 'myapp.forms.CustomUserCreationForm' ``` ### Custom Form Example ```python from django import forms from django.contrib.auth import get_user_model from lazysignup.forms import UserCreationForm as BaseUserCreationForm User = get_user_model() class CustomUserCreationForm(BaseUserCreationForm): email = forms.EmailField(required=True) first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) newsletter = forms.BooleanField(required=False, label="Subscribe to newsletter") class Meta(BaseUserCreationForm.Meta): model = User fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2') def save(self, commit=True): user = super().save(commit=False) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if commit: user.save() if self.cleaned_data.get('newsletter'): # Subscribe user to newsletter logic here pass return user def get_credentials(self): return { 'username': self.cleaned_data['username'], 'password': self.cleaned_data['password1'] } ``` ``` -------------------------------- ### Allow Lazy User Decorator for Views (Python) Source: https://github.com/danfairs/django-lazysignup/blob/master/docs/usage.rst The `allow_lazy_user` decorator marks a view to create temporary user accounts for anonymous users. It takes no arguments and is applied directly above the view function. Accessing such a view will generate a temporary user if the current user is anonymous. ```python from django.http import HttpResponse from lazysignup.decorators import allow_lazy_user @allow_lazy_user def my_view(request): return HttpResponse(request.user.username) ``` -------------------------------- ### Is Lazy User Utility Function (Python) Source: https://github.com/danfairs/django-lazysignup/blob/master/docs/usage.rst The `is_lazy_user` function from `lazysignup.utils` provides programmatic access to check if a user object represents a lazily created account. This is useful in Python view logic or tests. It accepts a user object as an argument. ```python from lazysignup.utils import is_lazy_user from django.contrib.auth.models import AnonymousUser def testIsLazyUserAnonymous(self): user = AnonymousUser() self.assertEqual(False, is_lazy_user(user)) ``` -------------------------------- ### Django Admin Integration for LazyUser Model Source: https://context7.com/danfairs/django-lazysignup/llms.txt The LazyUser model is automatically registered with the Django admin interface, providing a dedicated section to manage lazy users. Access it via the '/admin/lazysignup/lazyuser/' URL. The admin interface includes a list display showing the user and creation timestamp, and a cleanup action to delete selected lazy users and unconverted users older than the session cookie age. ```python # The LazyUserAdmin is automatically registered # Access at: /admin/lazysignup/lazyuser/ # Admin features: # - List display: user, created timestamp # - Action: "Delete selected lazy users and unconverted users older than SESSION_COOKIE_AGE" ``` -------------------------------- ### Allow Lazy User Decorator for Django Views Source: https://context7.com/danfairs/django-lazysignup/llms.txt The `@allow_lazy_user` decorator automatically creates temporary user accounts for anonymous users accessing decorated views. This allows anonymous users to interact with features requiring authentication, with `request.user` becoming an authenticated User object. ```python from django.http import HttpResponse, JsonResponse from lazysignup.decorators import allow_lazy_user @allow_lazy_user def shopping_cart(request): """ Anonymous users visiting this view will automatically get a temporary account. request.user will be an authenticated User object (not AnonymousUser). """ cart_items = request.user.cart_items.all() return JsonResponse({ 'username': request.user.username, 'is_authenticated': request.user.is_authenticated, # True 'is_anonymous': request.user.is_anonymous, # False 'cart_count': cart_items.count() }) @allow_lazy_user def save_preference(request): """Save user preferences - works for both lazy and regular users.""" if request.method == 'POST': # request.user is always authenticated here preference = request.POST.get('preference') request.user.profile.preference = preference request.user.profile.save() return HttpResponse('Saved', status=200) return HttpResponse('Method not allowed', status=405) ``` -------------------------------- ### Specify Custom User Creation Form in Django Settings Source: https://github.com/danfairs/django-lazysignup/blob/master/docs/usage.rst To use a custom user creation form with Django LazySignup, set the LAZYSIGNUP_CUSTOM_USER_CREATION_FORM setting in your Django settings file. This allows you to define your own form logic for user creation. ```python LAZYSIGNUP_CUSTOM_USER_CREATION_FORM = 'myproject.apps.myapp.forms.MyForm' ``` -------------------------------- ### Configure Custom User Model for Lazysignup (Django) Source: https://github.com/danfairs/django-lazysignup/blob/master/docs/user.rst Set the LAZYSIGNUP_USER_MODEL setting to specify a custom Django User model. This setting should be a dotted Django path to your model. If AUTH_USER_MODEL is already set to your custom model, this is not strictly necessary. Lazysignup requires the custom model's default manager to have a `create_user` method with the same signature as Django's UserManager. ```python LAZYSIGNUP_USER_MODEL = 'myapp.CustomUser' ``` -------------------------------- ### Restrict Django Views with @require_nonlazy_user Decorator Source: https://context7.com/danfairs/django-lazysignup/llms.txt The @require_nonlazy_user decorator ensures that only non-lazy (permanent) users can access a specific Django view. Lazy users are automatically redirected to a specified URL, typically for account conversion. This is useful for protecting sensitive features that require a fully registered account. ```python from django.http import HttpResponse from lazysignup.decorators import require_nonlazy_user @require_nonlazy_user('lazysignup_convert') # Redirect lazy users to conversion page def premium_features(request): """ Only permanent users can access premium features. Lazy users are redirected to create a real account first. """ return HttpResponse("""

Premium Dashboard

Welcome back, {}!

""".format(request.user.username)) @require_nonlazy_user('/convert/') def billing_settings(request): """Billing page - requires a permanent account.""" return HttpResponse('Billing Settings') ``` -------------------------------- ### Customize Django Lazy User Cleanup Command Source: https://context7.com/danfairs/django-lazysignup/llms.txt Extend the default 'remove_expired_users' management command in Django to implement custom logic for deleting expired lazy users. By subclassing `lazysignup.management.commands.remove_expired_users.Command` and overriding the `to_delete` method, you can define specific criteria for user deletion, such as checking for associated data like orders or cart items. The `handle` method can also be overridden for custom logging or notifications. ```python # Customize the cleanup behavior by subclassing the command from lazysignup.management.commands.remove_expired_users import Command as BaseCommand from lazysignup.models import LazyUser import datetime from django.conf import settings class Command(BaseCommand): """Custom cleanup command with additional logic.""" def to_delete(self): """Override to customize which users get deleted.""" # Default: delete users older than SESSION_COOKIE_AGE delete_before = datetime.datetime.now() - datetime.timedelta( seconds=settings.SESSION_COOKIE_AGE ) # Custom: Only delete users with no associated data return LazyUser.objects.filter( user__last_login__lt=delete_before, user__orders__isnull=True, # No orders user__cart_items__isnull=True, # Empty cart ).select_related('user') def handle(self, **options): """Override to add logging or notifications.""" count = self.to_delete().count() super().handle(**options) self.stdout.write(f"Deleted {count} expired lazy users") ``` -------------------------------- ### Run Django Lazy User Cleanup Management Command Source: https://context7.com/danfairs/django-lazysignup/llms.txt Execute the 'remove_expired_users' management command from your Django project's root directory to clean up stale, unconverted lazy user accounts. This command deletes users whose last login is older than the session cookie age defined in settings. It automatically handles the deletion of associated LazyUser records and related data. ```bash # Run from command line to remove expired lazy users python manage.py remove_expired_users # The command deletes users whose last_login is older than SESSION_COOKIE_AGE # This cascades to delete associated LazyUser records and related data ``` -------------------------------- ### Conditionally Display Content with is_lazy_user Template Filter Source: https://context7.com/danfairs/django-lazysignup/llms.txt The is_lazy_user template filter allows you to dynamically adjust the content displayed in your Django templates based on whether the current user is a lazy (temporary) user. This is commonly used to show prompts for account conversion or to hide features not available to temporary accounts. ```html {% load lazysignup_tags %} {# Example: Show different content based on user type #} {% if user|is_lazy_user %}
Temporary Account

Your data will be lost when you close your browser unless you create a permanent account.

{% endif %} ``` -------------------------------- ### Check User Status with is_lazy_user() Utility Function Source: https://context7.com/danfairs/django-lazysignup/llms.txt The is_lazy_user() function checks if a given user object represents a temporary, lazy user. It can be used in Python code to conditionally execute logic based on the user's account type. The function correctly identifies anonymous users and regular authenticated users as not lazy. ```python from lazysignup.utils import is_lazy_user from django.contrib.auth.models import AnonymousUser from django.contrib.auth import get_user_model User = get_user_model() def check_user_status(request): """Check various user states.""" user = request.user # Check if user is lazy if is_lazy_user(user): print("User is a temporary lazy user") return {'status': 'lazy', 'can_convert': True} elif user.is_anonymous: print("User is anonymous (not logged in)") return {'status': 'anonymous', 'can_convert': False} else: print("User is a regular authenticated user") return {'status': 'authenticated', 'can_convert': False} # In tests def test_lazy_user_detection(): """Test is_lazy_user with different user types.""" from lazysignup.models import LazyUser # Anonymous users are not lazy anon = AnonymousUser() assert is_lazy_user(anon) == False # Create a lazy user and verify detection user, username = LazyUser.objects.create_lazy_user() assert is_lazy_user(user) == True # Regular users are not lazy regular_user = User.objects.create_user('regular', 'email@test.com', 'password') assert is_lazy_user(regular_user) == False ``` -------------------------------- ### Require Lazy User Decorator for Django Views Source: https://context7.com/danfairs/django-lazysignup/llms.txt The `@require_lazy_user` decorator restricts view access to only temporary (lazy) users. Non-lazy users are redirected to a specified URL, optionally with custom keyword arguments. This decorator is often used in conjunction with `@allow_lazy_user`. ```python from django.http import HttpResponse from lazysignup.decorators import allow_lazy_user, require_lazy_user @require_lazy_user('account_dashboard') # Redirect non-lazy users to this URL name @allow_lazy_user def lazy_user_promo(request): """ Show special promotion only to temporary users encouraging them to register. Non-lazy users get redirected to their dashboard. """ return HttpResponse( """

Save your progress!

Create a permanent account to keep your data.

Create Account """ ) @require_lazy_user('/login/', permanent=False) # Redirect with custom kwargs @allow_lazy_user def temporary_workspace(request): """Workspace only available to temporary users.""" return HttpResponse('Welcome to your temporary workspace!') ``` -------------------------------- ### Is Lazy User Template Filter (Django Template) Source: https://github.com/danfairs/django-lazysignup/blob/master/docs/usage.rst The `is_lazy_user` template filter checks if a given user is a temporary, lazily created user. It's used within Django templates to conditionally render content based on the user's authentication status. Load the tag library using `{% load lazysignup_tags %}`. ```django {% load i18n lazysignup_tags %} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.