Django - User Registration with Modal Ajax

Viewed 53

my user registration with modal form does not validate/save. It only just close immediately when you save and nothing happens.

this is the views.py

from django.template.loader import render_to_string
from django.http import JsonResponse
from authentication.forms import CustomUserCreationForm
from django.contrib import messages
def CreateUser(request):
    data = dict()
    if request.method == "POST":
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            data["form_is_valid"] = True
            username = form.cleaned_data.get('username')
            messages.success(request, f'Your account has been created! You are now able to log in')
            return redirect('home/manage-users.html')
        else:
            data["form_is_valid"] = False
    else:
        form = CustomUserCreationForm()
    
    context = {'form': form}
    data["html_form"] = render_to_string('partial_modal/create-user.html', context, request=request)
    return JsonResponse(data)

Any tips how can I work this my code? Thank you.

1 Answers

The save method takes an argument which is "commit" it is True by default that means the form data will be saved into the database. What I have experienced is that sometimes it does not work properly so, instead of calling the save method on form instance try the following code.

myUser = form.save(commit = False)
myUser.save()
Related