api.
Real-time VerificationFrameworks

Django

Getting Started

Before integrating user.cleaning into your Django application, you'll need to install the requests library to make API calls. You can do this with pip:

pip install requests

Next, store your API key securely in your Django settings or environment variables. Never hardcode API keys directly in your source code:

.env
USER_CLEANING_API_KEY = "your-api-key"

Next, store your API key securely in your environment variables and load it in your application:

config.py
import os
USER_CLEANING_API_KEY = os.environ.get("USER_CLEANING_API_KEY", "")

If you don't have an API key yet, check out our Quickstart guide to generate one.

IP Forwarding for Rate Limiting

For user.cleaning's rate limiting to work correctly, you need to forward the real client IP with each request. Add this helper function to extract the client IP:

utils.py
def get_client_ip(request):
    x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
    if x_forwarded_for:
        return x_forwarded_for.split(",")[0].strip()
    return request.META.get("HTTP_X_REAL_IP") or request.META.get("REMOTE_ADDR") or "unknown"

Production: If you're behind nginx, Cloudflare, or a load balancer, X-Forwarded-For is set automatically.

Development/testing: Without a reverse proxy forwarding X-Forwarded-For, the integration will see your server's IP instead of actual client IPs. This means all requests appear to come from the same IP, and after 5 disposable email attempts, all registrations will be blocked until the IP is unbanned.

If you experience unexpected registration blocks, verify your reverse proxy is forwarding client IPs correctly. You can unban blocked IPs at API Settings and configure number of registration attempts before block or disable it completely at Color Configuration.

Creating the Validation Function

Now let's create a helper function that communicates with the user.cleaning API. This function takes an email and client IP as input and returns the validation result:

utils.py
import os
import requests

def check_email(email: str, client_ip: str) -> dict:
    """Validate email with user.cleaning API."""
    try:
        response = requests.post(
            "https://api.user.cleaning/v1/email/check",
            headers={"Authorization": f"Bearer {settings.USER_CLEANING_API_KEY}"},
            json={"email": email, "ip": client_ip},
            timeout=5
        )
        if response.status_code == 403:
            data = response.json()
            return {"category": "banned", "message": data.get("detail", "Access denied")}
        response.raise_for_status()
        return response.json()
    except requests.RequestException:
        return {"category": "white"}

The API responds with a JSON object containing a category field, which tells you whether the email should be accepted, rejected, or treated with caution.

Integration Approaches

Validating Emails in Django Forms

The most straightforward way to block disposable emails is to add validation directly to your Django forms. Django's form validation system makes this really clean.

Let's say you have a registration form that looks like this:

forms.py
from django import forms

class RegistrationForm(forms.Form):
    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)

To add disposable email detection, pass the request to your form and validate in clean_email:

forms.py
from django import forms
from django.core.exceptions import ValidationError

class RegistrationForm(forms.Form):
    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)

    def __init__(self, *args, request=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
    
    def clean_email(self):
        email = self.cleaned_data["email"]
        client_ip = get_client_ip(self.request) if self.request else "unknown"
        result = check_email(email, client_ip)
        
        if result["category"] == "black":
            raise ValidationError(
                "Please use a permanent email address. Disposable emails are not allowed."
            )
        
        return email

In your view, pass the request when instantiating the form:

views.py
def register_view(request):
    form = RegistrationForm(request.POST or None, request=request)
    # ...

When a user submits the form with a disposable email, they'll see your custom error message instead of being allowed to register.

Validating Emails in Views

In your signup view, call get_client_ip(request) and check_email(email, client_ip) before creating the user:

views.py
def signup(request):
    if request.method == 'POST':
        email = request.POST.get('email', '')
        client_ip = get_client_ip(request)
        
        result = check_email(email, client_ip)
        
        if result["category"] == "banned":
            # IP banned or rate limited
            return render(request, 'signup.html', {'error': result["message"]})
        
        if result["category"] == "black":
            return render(request, 'signup.html', {'error': 'Disposable emails are not allowed'})
        
        if result["category"] == "grey":
            # Require additional verification
            pass
        
        # 'white' — proceed normally
        # create_user(email, password)
        
    return render(request, 'signup.html')

Understanding the Results

The category field can have three possible values:

  • black — This is a disposable or temporary email address that should be blocked
  • grey — Suspicious patterns were detected (like alias chains or plus addressing), consider requiring additional verification
  • white — The email looks legitimate and can be accepted without restrictions

For a complete description of the output data structure and all available fields, see our Categories Reference.

Now that you understand what the API returns, let's look at different ways to integrate this validation into your Django application.

This approach is particularly useful when you want to handle grey-listed emails differently from blacklisted ones. For example, you might allow registration but require phone verification for suspicious emails.

On this page