-
Notifications
You must be signed in to change notification settings - Fork 46
Description
This doesn't seem to be implemented. Is anybody working on it? If not, I can submit a PR myself. I'm thinking something like this will work just fine:
from django import forms
from django.http import HttpRequest, HttpResponse
from django.views import View
from django.shortcuts import redirect
import inertia
class ExampleForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
class ExampleView(View):
def post(self, request: HttpRequest) -> HttpResponse:
form = ExampleForm(request.POST)
# Option A, more explicit
if not form.is_valid():
raise inertia.ValidationError(form.errors)
# Option B, automatically raise the error
inertia.validate(form)
# use form.data here...
return redirect("some_route_name")For this to work properly in all cases we need to know the route where the user is coming from. Django doesn't store the previous route in the session like Laravel does, so there's no equivalent of Laravel's return back()->withErrors(). You can emulate the return back() part using the HTTP Referer header as suggested here or by sending a next=URL query param in the request as suggested here.
However, the Referer header can't be trusted in all cases and the next query param requires changing the frontend code. So I'm thinking of 2 possible solutions, either implement Laravel's behavior of storing the previous URL in the session to provide a return back() function or just provide the route at validation time:
inertia.validate(form, error_url="some_route_name_or_url")Second option is more verbose but easier to implement, and it can coexist with the first option since we could make error_url=None by default and grab the route from the session. I guess all this could be a separate middleware that basically catches the inertia.ValidationError, allowing the users to opt-in by adding the middleware to settings.py. Otherwise it could be integrated into the current inertia.middleware.InertiaMiddleware.
Edit:
Issue #21 is related to this.