python
28 lines · 1 tab
Priya Sharma
Jan 2026
1 tab
from django import forms
from .models import Event
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['title', 'description', 'start_date', 'end_date', 'capacity']
def clean_capacity(self):
capacity = self.cleaned_data.get('capacity')
if capacity and capacity < 1:
raise forms.ValidationError('Capacity must be at least 1')
return capacity
def clean(self):
cleaned_data = super().clean()
start_date = cleaned_data.get('start_date')
end_date = cleaned_data.get('end_date')
if start_date and end_date:
if end_date <= start_date:
self.add_error(
'end_date',
'End date must be after start date'
)
return cleaned_data
1 file · python
Explain with highlit
I use clean_<fieldname>() to validate individual fields and clean() to validate field combinations. Raising ValidationError shows the message to the user near the appropriate field. For cross-field validation (like 'end date must be after start date'), I override clean() and attach errors with add_error(). I keep validation logic in forms rather than models because it's often context-dependent. Using cleaned_data ensures I'm working with validated, type-converted values. This pattern keeps forms self-contained and easy to test.
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
ruby
class SignupForm
include ActiveModel::Model
include ActiveModel::Attributes
attribute :account_name, :string
attribute :email, :string
Shallow Controller, Deep Params: Form Object Pattern
rails
activemodel
form-object
by codesnips
3 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
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Validation Example</title>
<style>
HTML forms with validation and accessibility
html
forms
validation
by Alex Chang
1 tab
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
Share this code
Here's the card — post it anywhere.