Source code for django_landing_simple.error_simple.views

"""
This module provides centralized error handling for simple web applications, implementing custom
error pages for HTTP status codes and test triggers for development/testing environments. It ensures
users receive informative, branded error messages when issues occur.

**Business Context:**

Professional error handling is crucial for user experience and application credibility. When users
encounter errors (page not found, server errors, permission issues), they receive user-friendly error
pages that maintain the application's brand experience and provide helpful guidance. This module
ensures consistent error handling across the entire application.

**Key Business Value:**

1. **User Experience:**

- Professional, branded error pages instead of generic browser errors
    - Clear messaging about what went wrong
    - Guidance on how to proceed (return home, contact support)
    - Consistent design with application theme
    - Multi-language support for error messages

2. **Development & Testing:**

- Test trigger views for QA and development
    - Easy error page validation before production
    - Consistent error handling patterns
    - Quick verification of error page appearance

3. **Production Reliability:**

- Graceful error handling prevents application crashes
    - User-friendly messages maintain application trust
    - Clear error identification for troubleshooting
    - Professional appearance during failures

**Error Handling:**

Production Error Handlers (Called by Django automatically):

- :func:`error_400_view`: Bad Request - Malformed client request

- :func:`error_403_view`: Forbidden - Permission denied

- :func:`error_404_view`: Not Found - Resource doesn't exist

- :func:`error_500_view`: Internal Server Error - Application error

- :func:`error_502_view`: Bad Gateway - Proxy/upstream server error

- :func:`error_503_view`: Service Unavailable - Temporary maintenance/overload

Test Trigger Views (For development/testing only):

- :func:`trigger_400_test`: Generate test 400 error

- :func:`trigger_403_test`: Generate test 403 error

- :func:`trigger_404_test`: Generate test 404 error

- :func:`trigger_500_test`: Generate test 500 error

- :func:`trigger_502_test`: Generate test 502 error

- :func:`trigger_503_test`: Generate test 503 error

**Common Error Scenarios:**

- **400 Bad Request:** User submits malformed data or suspicious operation
- **403 Forbidden:** User attempts unauthorized action
- **404 Not Found:** User navigates to non-existent page or resource
- **500 Internal Server Error:** Application logic error or backend failure
- **502 Bad Gateway:** Backend server connection issues
- **503 Service Unavailable:** Application maintenance or overload

**Technical Features:**

- Custom error templates with application branding
- HTTP status code preservation
- Exception handling with Django's exception framework
- Test routes for error page validation
- Integration with Django's error handling middleware
- Multi-language support via Django i18n

**Integration:**

Error views integrate with:
- Django's URL routing for error handlers
- Template system for consistent branding
- Internationalization framework for multi-language errors
- Django settings for error handler configuration

**Security:**

- No sensitive information exposed in error messages
- Test trigger views should be disabled in production
- Safe exception handling prevents information disclosure
- Generic error messages for security

**Production Configuration:**

In :mod:`settings.urls`, configure error handlers:

- handler400 = :func:`error_400_view`
- handler403 = :func:`error_403_view`
- handler404 = :func:`error_404_view`
- handler500 = :func:`error_500_view`

**Important:** Test trigger views must be removed from production URL configuration.

**Testing Error Pages:**

During development, access test triggers via URL patterns:
- /error/400/ - Test Bad Request page
- /error/403/ - Test Forbidden page
- /error/404/ - Test Not Found page
- /error/500/ - Test Internal Server Error page
- /error/502/ - Test Bad Gateway page
- /error/503/ - Test Service Unavailable page

**Best Practices:**

- Always test error pages before production deployment
- Ensure error pages match application branding
- Provide clear, helpful guidance to users
- Never expose technical details in error messages
- Remove test trigger URLs from production
- Use appropriate HTTP status codes
- Keep error messages user-friendly and non-technical
"""

# Initialize Django settings if running standalone (e.g., in Thonny IDE)
# This allows the module to be imported for inspection without running Django server
import sys
import os
if __name__ == "__main__" or 'django.conf.settings' not in sys.modules or not hasattr(sys.modules.get('django.conf.settings', None), 'configured'):
    import django
    from django.conf import settings
    if not settings.configured:
        # Add the project root to Python path
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        if project_root not in sys.path:
            sys.path.insert(0, project_root)
        # Set the Django settings module
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.settings')
        # Setup Django
        django.setup()

from django.shortcuts import render
from django.http      import HttpResponseNotFound, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseServerError
from django.core.exceptions import SuspiciousOperation, PermissionDenied

# used for internationalization (i18n) and localization (l10n)
from django.utils             import translation
# for the use of the gettext function to mark text for translation
from django.utils.translation import gettext as _
# set the desired language for templates
from django.utils.translation import activate, deactivate


[docs] def error_400_view(request, exception): """ Error handling for 400 error. """ return render(request, 'error_400.html', status=400)
[docs] def error_403_view(request, exception): """ Error handling for 403 error. """ return render(request, 'error_403.html', status=403)
[docs] def error_404_view(request, exception): """ Error handling for 404 error. """ return render(request, 'error_404.html', status=404)
[docs] def error_500_view(request, *args, **argv): """ Error handling for 500 error. """ return render(request, 'error_500.html', status=500)
[docs] def error_502_view(request, *args, **argv): """ Error handling for 502 Bad Gateway error. """ return render(request, 'error_502.html', status=502)
[docs] def error_503_view(request, *args, **argv): """ Error handling for 503 Service Unavailable error. """ return render(request, 'error_503.html', status=503)
# Test trigger views (for testing error pages only)
[docs] def trigger_400_test(request): """ Test view to trigger a 400 Bad Request error. This view should only be used in testing environments. """ raise SuspiciousOperation("Test 400 error")
[docs] def trigger_403_test(request): """ Test view to trigger a 403 Forbidden error. This view should only be used in testing environments. """ raise PermissionDenied("Test 403 error")
[docs] def trigger_404_test(request): """ Test view to trigger a 404 Not Found error. This view should only be used in testing environments. """ return render(request, 'error_404.html', status=404)
[docs] def trigger_500_test(request): """ Test view to trigger a 500 Internal Server Error. This view should only be used in testing environments. """ raise Exception("Test 500 error")
[docs] def trigger_502_test(request): """ Test view to manually trigger a 502 Bad Gateway error. This view should only be used in testing environments. Note: Real 502 errors occur at the web server level, not in Django. """ return render(request, 'error_502.html', status=502)
[docs] def trigger_503_test(request): """ Test view to manually trigger a 503 Service Unavailable error. This view should only be used in testing environments. Note: Real 503 errors typically occur at the web server level for maintenance mode. """ return render(request, 'error_503.html', status=503)