I can't save my form to the database

Hello I am trying to create a register form but when I try to save the user to my database but the database is always empty even tough I get no errors and bugs. I believe I am saving the user to somewhere because when I try to create a user with the same information I get an error saying there is already a user with that username.

RegisterPage.html

<form method="post">
        {% csrf_token %}
        <div class="input-group" style="padding: 15px">
            <input type="text" name="username" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1">
        </div>
        <div class="input-group" style="padding: 15px">
            <input type="email" name="email" class="form-control" placeholder="E posta" aria-label="E posta" aria-describedby="basic-addon1">
        </div>
        <div class="input-group" style="padding: 15px">
            <input type="password" name="password1" class="form-control" placeholder="Password" aria-label="Password" aria-describedby="basic-addon1">
        </div>
        <div class="input-group" style="padding: 15px">
            <input type="password" name="password2" class="form-control" placeholder="Confirm Password" aria-label="Confirm Password" aria-describedby="basic-addon1">
        </div>

        <a href="http://localhost:8000">Zaten bir hesabın varmı?</a>
        <div class="card-body">
            <button type="submit" class="btn btn-primary">Kayıt Ol</button>
        </div>
    </form>

Forms\views.py

class UserRegistrationForm(forms.ModelForm):
password1 = forms.CharField(label='password1', widget=forms.PasswordInput)
password2 = forms.CharField(label='password2', widget=forms.PasswordInput)

class Meta:
    model = User
    fields = ['username', 'email', 'password1', 'password2']

def clean_password2(self):
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 != password2:
        self.add_error('password2', 'Şifreler uyuşmuyor')
    return password2

def save(self, commit=True):
    user = super().save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
    return user

Login\models.py

class User(models.Model):
userid = models.AutoField(db_column='UserId', primary_key=True)  # Field name made lowercase.
username = models.CharField(db_column='UserName', max_length=20, db_collation='Turkish_CI_AS')  # Field name made lowercase.
password = models.CharField(db_column='Password', max_length=20, db_collation='Turkish_CI_AS')  # Field name made lowercase.
email = models.CharField(db_column='Email', max_length=20, db_collation='Turkish_CI_AS')  # Field name made lowercase.
favourites = models.TextField(db_column='Favourites', blank=True, null=True)  # Field name made lowercase. This field type is a guess.
recipes = models.TextField(db_column='Recipes', blank=True, null=True)  # Field name made lowercase. This field type is a guess.

class Meta:
    managed = False
    db_table = 'User'

Login\views.py

def register(request):
if request.method == 'POST':
    form = UserRegistrationForm(request.POST)
    if form.is_valid():
        form.save()
        messages.success(request, 'Account created successfully')
        return redirect('login')
    else:
        print(form.errors)
        return render(request, 'RegisterPage.html', {'form': form, 'errors': form.errors})

else:
    form = UserRegistrationForm()

return render(request, 'RegisterPage.html', {'form': form})

FoodRecipeApp\settings.py

DATABASES = {
"default": {
    "ENGINE": "mssql",
    "NAME": "FoodRecipeDB",
    "USER": "",
    "PASSWORD": "",
    "HOST": "localhost",
    "PORT": "1433",
    "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server",
    },
},
}

If there is something I am missing please let me know.

Also this is the warning print(form.errors) gives me in the terminal if I try to register a username I already tried before. Clearly I am saving it to somewhere but where ?

  • username
    • A user with that username already exists.

The first issue is, and it may just be an issue of how you’ve pasted this code into your message, your indentation isn’t correct in your code. (I’m willing to assume that it’s actually right in your code, otherwise, you’d be facing other issues.)

What specifically are you looking at that gives you the indication that the database is empty?

Do you have your settings file set to use your User model as the system’s User class? (Show the setting here)

Hello yes the indantation is correct, the project is up and running in pycharm. According to my understanding of django when I click to Kayıt Ol(Register) button in the html form the user’s information should appear in my database User table.

This is the settings.py file.

"""
Django settings for FoodRecipeApp project.

Generated by 'django-admin startproject' using Django 5.0.2.

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-kf0n%=a#qkmp^0pnllp)(y%14)*k8nyx6eev-nh=-9jw6i-4nf'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"Login.apps.LoginConfig",
"Forms.apps.FormsConfig",
"django_extensions"
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'FoodRecipeApp.urls'

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [BASE_DIR / 'templates']
    ,
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
]

WSGI_APPLICATION = 'FoodRecipeApp.wsgi.application'


# Database

DATABASES = {
"default": {
    "ENGINE": "mssql",
    "NAME": "FoodRecipeDB",
    "USER": "",
    "PASSWORD": "",
    "HOST": "localhost",
    "PORT": "1433",
    "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server",
    },
},
}

# Password validation

AUTH_PASSWORD_VALIDATORS = [
{
    'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)

STATIC_URL = 'static/'

# Default primary key field type

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

It looks to me like you’re trying to replace Django’s User model with your own.

To do so, you need to read Customizing authentication in Django | Django documentation | Django

What button in what form?

Again, you wrote:

What specifically are you looking at?

Yes that was the issue i fixed it now thanks to the documentation thank you very much sir. I can now save it to my database with this and fixing my custom user model.

AUTH_USER_MODEL = 'Login.User'