Django + React: How to handle CSRF tokens in API requests?

Answered
43

I'm working on a Django project and encountering an issue with Django forms. Here's my current implementation:


# models.py
from django.db import models

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField()
    
# Signal handler
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

The specific error I'm getting is: "django.urls.exceptions.NoReverseMatch: Reverse for 'article_detail' not found"

I've already tried the following approaches:

  • Checked Django documentation and Stack Overflow
  • Verified my database schema and migrations
  • Added debugging prints to trace the issue
  • Tested with different data inputs

Environment details:

  • Django version: 5.0.1
  • Python version: 3.11.0
  • Database: PostgreSQL 15
  • Operating system: macOS Ventura

Has anyone encountered this before? Any guidance would be greatly appreciated!

A
Asked by admin
Bronze 75 rep

5 Answers

17

To optimize Django QuerySets and avoid N+1 problems, use select_related() for ForeignKey and OneToOneField, and prefetch_related() for ManyToManyField and reverse ForeignKey:

# Bad: N+1 query problem
for book in Book.objects.all():
    print(book.author.name)  # Each iteration hits the database

# Good: Use select_related for ForeignKey
for book in Book.objects.select_related('author'):
    print(book.author.name)  # Single query with JOIN

# Good: Use prefetch_related for ManyToMany
for book in Book.objects.prefetch_related('categories'):
    for category in book.categories.all():
        print(category.name)  # Optimized with separate query

You can also use only() to limit fields and defer() to exclude heavy fields:

# Only fetch specific fields
Book.objects.only('title', 'author__name').select_related('author')

# Defer heavy fields
Book.objects.defer('content', 'description')
A
Answered by abdullah3 1 week, 4 days ago
Bronze 90 rep
26

The choice between Django signals and overriding save() depends on your use case:

Use save() method when:

  • The logic is directly related to the model
  • You need to modify the instance before saving
  • The operation is essential for data integrity
class Article(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    
    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs)

Use signals when:

  • You need decoupled logic
  • Multiple models need the same behavior
  • You're working with third-party models
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
A
Answered by abadi 1 week, 4 days ago
Bronze 60 rep

Comments

joseph: This Django transaction approach worked perfectly for my payment processing system. Thanks! 1 week, 4 days ago

24

The choice between Django signals and overriding save() depends on your use case:

Use save() method when:

  • The logic is directly related to the model
  • You need to modify the instance before saving
  • The operation is essential for data integrity
class Article(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    
    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs)

Use signals when:

  • You need decoupled logic
  • Multiple models need the same behavior
  • You're working with third-party models
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
W
Answered by william 1 week, 4 days ago
Newbie 40 rep

Comments

joseph: I'm getting a similar error but with PostgreSQL instead of SQLite. Any differences in the solution? 1 week, 4 days ago

20

Here's a comprehensive approach to implementing JWT authentication in Django REST Framework:

# settings.py
INSTALLED_APPS = [
    'rest_framework',
    'rest_framework_simplejwt',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

from datetime import timedelta
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': True,
}
# urls.py
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    path('api/token/', TokenObtainPairView.as_view()),
    path('api/token/refresh/', TokenRefreshView.as_view()),
]
# Custom serializer for additional user data
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        token['username'] = user.username
        token['email'] = user.email
        return token
L
Answered by lisa_data 1 week, 4 days ago
Bronze 50 rep

Comments

abdullah: I'm getting a similar error but with PostgreSQL instead of SQLite. Any differences in the solution? 1 week, 4 days ago

abaditaye: I'm getting a similar error but with PostgreSQL instead of SQLite. Any differences in the solution? 1 week, 4 days ago

12

The difference between threading and multiprocessing in Python is crucial for performance:

Threading (shared memory, GIL limitation):

import threading
import time

def io_bound_task(name):
    print(f'Starting {name}')
    time.sleep(2)  # Simulates I/O operation
    print(f'Finished {name}')

# Good for I/O-bound tasks
threads = []
for i in range(3):
    t = threading.Thread(target=io_bound_task, args=(f'Task-{i}',))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

Multiprocessing (separate memory, no GIL):

import multiprocessing
import time

def cpu_bound_task(name):
    # CPU-intensive calculation
    result = sum(i * i for i in range(1000000))
    return f'{name}: {result}'

# Good for CPU-bound tasks
if __name__ == '__main__':
    with multiprocessing.Pool(processes=4) as pool:
        tasks = [f'Process-{i}' for i in range(4)]
        results = pool.map(cpu_bound_task, tasks)
        print(results)

Concurrent.futures (unified interface):

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

# For I/O-bound tasks
with ThreadPoolExecutor(max_workers=4) as executor:
    futures = [executor.submit(io_bound_task, f'Task-{i}') for i in range(4)]
    results = [future.result() for future in futures]

# For CPU-bound tasks
with ProcessPoolExecutor(max_workers=4) as executor:
    futures = [executor.submit(cpu_bound_task, f'Process-{i}') for i in range(4)]
    results = [future.result() for future in futures]
J
Answered by jane_smith 1 week, 4 days ago
Bronze 60 rep

Your Answer

You need to be logged in to answer questions.

Log In to Answer

Related Questions

Hot Questions

No hot questions available.