0

I am trying to make a custom registration form in Django, using HTML and CSS and not Django's form.as_p. I have the following code in views.py:

def register(request):
   if request.POST:
       username = request.POST['username']
       email = request.POST['email']
       password = request.POST['password']
       password_confirm = request.POST['password-confirm']
       if(valid_form(username, email, password, password_confirm)) {
          #create the new user
       } else {
          #send some error message
       }    
return render(request, 'index.html')

I have my own function valid_form to check if the form fields entered by the user are valid. However, I am not sure how I can create the new user using a custom User Model. In all of the code examples regarding registration forms I have seen something like this:

def register(request):
if request.method == 'POST':
    form = UserCreationForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('main-page')
else:
    form = UserCreationForm()
return render(request, 'users/register.html', {'form': form})

Where form.save() is used to create the new user. I have the following model for a user in models.py:

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=200, null=True)
    email = models.EmailField(max_length=70, null=True)

How can I create a new CustomUser after validating form data? Any insights are appreciated.

ceno980
  • 2,003
  • 1
  • 19
  • 37
  • Can you show us your `UserCreationForm`? In essence, you need to make it into a `CustomUserCreationForm` by adding the required fields or use a ModelForm. – Kent Shikama Nov 10 '19 at 23:54
  • I am not using a UserCreationForm. I am not using Django's form model. Is there any way to create a CustomUser upon sign in without using Django's form model? – ceno980 Nov 11 '19 at 00:34
  • Does this answer your question? [How to get value from form field in django framework?](https://stackoverflow.com/questions/4706255/how-to-get-value-from-form-field-in-django-framework) – Kent Shikama Nov 11 '19 at 00:37
  • Or are you just interested in seeing the contents of `request.body` without a form? – Kent Shikama Nov 11 '19 at 00:39
  • Or do you just want to know how to create an object in Django? https://docs.djangoproject.com/en/2.2/topics/db/queries/#creating-objects – Kent Shikama Nov 11 '19 at 00:40
  • I would like to know how to save a CustomUser. In Django's User model you can create a new user, do user.set_password() and user.save() after validating form data. I would like to know how to do something similar but with the CustomUser model. – ceno980 Nov 11 '19 at 00:47
  • How come you can't just do `CustomUser.objects.create(field1=..., ...)`? See the link above. – Kent Shikama Nov 11 '19 at 01:01

0 Answers0