Is it possible to feed data from a React POST request into a Django form without rendering that form on the frontend?

I am working on a basic login form for a hybrid React/Django web app. I would like to use the built in data-cleaning and validating methods of the Django LoginForm, but our frontend is pure React. Everything works as far as logging in, but I am feeding the raw body data into the authenticate function as shown here.

def login_view(request):
    if request.method == "POST":
        form_data = json.loads(request.body.decode('utf-8'))
        user = authenticate(request, email=form_data["username"], password=form_data["password"])
        if user == None:
            request.session["invalid_user"] = 1
            logging.warning("Login form contains no user")
        login(request, user)

My question is, is there any way to feed this form_data into the Django native LoginForm when I instantiate it? I would prefer to not recode all of the input validation that Django does already.

I've tried instantiating a LoginForm like so:

form = LoginForm(data=form_data)

And then tried running form.full_clean(), but it doesn't seem to work. Any help would be greatly appreciated, thank you!

The issue was actually a difference in the variable names between the rendered React form and the Django LoginForm I had defined. One was username and password, the other email and password. With that in mind the usual way of working with forms works great!

if request.method == "POST":
    form_data = json.loads(request.body.decode('utf-8'))
    form = LoginForm(data=form_data)
    if form.is_valid():
        email = form.cleaned_data["email"]
        password = form.cleaned_data["password"]
        user = authenticate(request, email=email, password=password)
        if user is not None:
            login(request, user)
Back to Top