inertiajs / inertia-django

The Django adapter for Inertia.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How To Use Form Using inertia-django?

rvyhvn opened this issue · comments

Not an issue but just asking help. I got confused about implementing Django's form to use in my Vue.js front-end using Inertia.js, could someone give me an example about it? Here i got a simple model in models.py:

from django.db import models


class Post(models.Model):
    title = models.CharField(max_length=150)

    def __str__(self):
        return f"{self.id}. {self.title}"

and PostForm class in forms.py:

from django import forms
from .models import Post


class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = [
            'title',
        ]

When I'm using the form as props/context I got error: Object of type PostForm is not JSON serializable. I've tried using useForm() that Inertia.js have, I got an empty querydict but the response status is 200.

Okay, for anyone confused using form in django i think i found the solution. Just use inertia's useForm function and the request sent to Django is in the body. So my views.py would look like this:

class BlogCreateView(View):
    def get(self, request):
        post_list = Post.objects.all()
        return render(
            request, "Blog/Create", {"post_list": post_list, "title": "Create Post"}
        )

    def post(self, request):
        json_data = json.loads(request.body.decode("utf-8"))
        return render(request, "Blog/Create", {"title": json_data["title"]})

Haha sorry for posting issue here, i'm noob got stuck like 4 days about this.
Issue closed by myself.

@rvyhvn I am a bit curious about how do you display errors in the form?

@rvyhvn I am a bit curious about how do you display errors in the form?

The error or exception that might raised is handled in the back-end and the front-end. I forgot how cuz I don't use django anymore but the principle is when you validate something or showing error, it handled twice: in the back-end and the front-end. The backend might give some response error code and the front-end can validate the error. The error code could be given as context/props to FE.

CMIIW.