0
votes

Trying to add new User (using Django default User model).

#api/views.py
@csrf_exempt
@api_view(['GET', 'POST', ])
def signup(request):
    print(request.POST)
    if request.method == 'POST':
        form = UserCreationForm(data=request.POST)
        if form.is_valid():
            form.save()
            return Response('created new user')
        else:
            return Response('did not')

Here is the form. I am not using raw html, it is a React component

        <form className="register-form" noValidate action="api/register/"
            method="post" autoComplete="off">
                <input type="text" name="username"></input>
                <input type="password" name="password"></input>
                <input type="submit" value="Submit"></input>
        </form>

clicking submit successfully sends a post request to api/register, which in urls.py points it to views.signup.

form.is_valid is always evaluating to false, so the User isn't getting created. As far as I can tell, the only required fields to create the User are username and password. I have also tried removing the label "data" in UserCreationForm(data=request.POST). This doesn't work either. Where am I going wrong?

1

1 Answers

0
votes

Solved by printing to console and checking errors in signup function

        print(request.POST)
        print(form.errors)
        print(form.non_field_errors)

User model actually requires username, password1, and password 2. Changed form to

<form className="register-form" noValidate action="api/register/"
            method="post" autoComplete="off">
                <input type="text" name="username"></input>
                <input type="password" name="password1"></input>
                <input type="password" name="password2"></input>
                <input type="submit" value="Submit"></input>
        </form>

which solved the issue