Form validation
This commit is contained in:
@ -1,7 +1,66 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Optional
|
||||
|
||||
from django.core.handlers.wsgi import WSGIRequest
|
||||
from django.http import HttpResponse
|
||||
from django.shortcuts import render
|
||||
|
||||
from project.main.views.demo_view_base import DemoViewBase
|
||||
|
||||
|
||||
@dataclass
|
||||
class Validation:
|
||||
validated: bool = False
|
||||
|
||||
name: Optional[str] = None
|
||||
consent: Optional[bool] = None
|
||||
age: Optional[int] = None
|
||||
|
||||
name_error: Optional[str] = None
|
||||
age_error: Optional[str] = None
|
||||
consent_error: Optional[str] = None
|
||||
|
||||
|
||||
class FormValidationView(DemoViewBase):
|
||||
template_name = "main/form_validation.html"
|
||||
active_section = "form-validation"
|
||||
title = "Form Validation"
|
||||
|
||||
def get_context_data(self, **kwargs) -> dict[str, Any]:
|
||||
context = super().get_context_data(**kwargs)
|
||||
context.update(
|
||||
{
|
||||
"validation": Validation(),
|
||||
}
|
||||
)
|
||||
return context
|
||||
|
||||
def post(self, request: WSGIRequest, *args, **kwargs) -> HttpResponse:
|
||||
validation = Validation(
|
||||
validated=True,
|
||||
name=request.POST.get("name", ""),
|
||||
age=request.POST.get("age", ""),
|
||||
consent=request.POST.get("consent") == "on",
|
||||
)
|
||||
|
||||
if len(validation.name) < 3 or len(validation.name) > 10:
|
||||
validation.name_error = "Name must be between 3 and 10 chars long"
|
||||
|
||||
try:
|
||||
age = int(validation.age)
|
||||
except ValueError:
|
||||
validation.age_error = "Invalid integer"
|
||||
else:
|
||||
if age < 1 or age > 100:
|
||||
validation.age_error = "Age should be between 1 and 100"
|
||||
|
||||
if not validation.consent:
|
||||
validation.consent_error = "You should consent"
|
||||
|
||||
return render(
|
||||
context={
|
||||
"validation": validation,
|
||||
},
|
||||
template_name="main/form_validation_content.html",
|
||||
request=request,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user