python
45 lines · 2 tabs
Priya Sharma
Jan 2026
2 tabs
from django.core.exceptions import ValidationError
def validate_file_size(file):
"""Limit file size to 5MB."""
max_size_mb = 5
if file.size > max_size_mb * 1024 * 1024:
raise ValidationError(f'File size cannot exceed {max_size_mb}MB')
def validate_image_extension(file):
"""Allow only specific image formats."""
allowed_extensions = ['.jpg', '.jpeg', '.png', '.gif']
file_extension = file.name.lower().split('.')[-1]
if f'.{file_extension}' not in allowed_extensions:
raise ValidationError(
f'File extension .{file_extension} is not allowed. '
f'Allowed extensions: {", ".join(allowed_extensions)}'
)
import os
import uuid
from django.db import models
from core.validators import validate_file_size, validate_image_extension
def user_avatar_path(instance, filename):
"""Generate unique path for user avatar."""
ext = filename.split('.')[-1]
filename = f'{uuid.uuid4()}.{ext}'
return os.path.join('avatars', str(instance.user.id), filename)
class Profile(models.Model):
user = models.OneToOneField('auth.User', on_delete=models.CASCADE)
bio = models.TextField(blank=True)
avatar = models.ImageField(
upload_to=user_avatar_path,
validators=[validate_file_size, validate_image_extension],
null=True,
blank=True
)
def __str__(self):
return f'{self.user.username} Profile'
2 files · python
Explain with highlit
File uploads require careful validation for security. I validate file size using a custom validator and check content type. Using FileField or ImageField, Django handles storage automatically. I configure MEDIA_ROOT and MEDIA_URL for development. For production, I use django-storages with S3 or similar. The upload_to parameter can be a callable for dynamic paths. I generate unique filenames to avoid collisions. For large files, I consider chunked uploads or background processing. Always validate file content, not just extension, to prevent malicious uploads.
Related snips
python
import os
import stat
for root, _dirs, files in os.walk('/etc'):
for name in files:
path = os.path.join(root, name)
Python security audit script for exposed risky filesystem state
python
auditing
host-security
by Kai Nakamura
1 tab
python
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
cost = models.DecimalField(max_digits=10, decimal_places=2)
margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)
Django model signals vs overriding save
django
python
models
by Priya Sharma
2 tabs
python
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
Django URL namespacing and reverse lookups
django
python
urls
by Priya Sharma
3 tabs
python
import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment
class PostType(DjangoObjectType):
Django GraphQL with Graphene
django
python
graphql
by Priya Sharma
2 tabs
go
package files
import (
"context"
"time"
Presigned S3 upload URLs (AWS SDK v2)
go
aws
s3
by Leah Thompson
1 tab
python
from django.db.models import Count, Avg, Sum, Q, F
from django.views.generic import TemplateView
from products.models import Product, Order, OrderItem
class DashboardView(TemplateView):
Django aggregation with annotate for statistics
django
python
database
by Priya Sharma
1 tab
Share this code
Here's the card — post it anywhere.