向django数据库写入数据

问题描述 投票:0回答:0

我有一个网站项目,但它还是原始的。问题是我写了一个单独的用户注册页面,这个页面的数据被写入数据表,但是一旦在forms.py中我添加了额外的参数比如-密码中至少有8个字符,然后数据停止写入数据库。

我已尽我所能,我已将其添加到模板表单 {% if form.errors%}。但傻是没有错的。而且我也逐渐对每个参数进行了清理,但也无济于事。我来这里是为了找出错误是什么,帮助我完成下面所有必要的代码,如果您需要什么,请写信给我,我会把它扔掉。我也做了迁移

这是 forms.py 用户应用程序

from .models import UserProfile
from django import forms
from django.forms import ModelForm, TextInput
from django.core.validators import RegexValidator, EmailValidator


class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = ['email', 'password', 'password2', 'first_name', 'last_name', 'phone_number']

        widgets = {
            "email": TextInput(attrs={
                'class': 'form',
                'placeholder': 'Email',
                'type': 'text'
            }),
            "password": TextInput(attrs={
                'class': 'form',
                'placeholder': 'Password',
                'type': 'password'
            }),
            "password2": TextInput(attrs={
                'class': 'form',
                'placeholder': 'rePassword',
                'type': 'password'
            }),

            "first_name": TextInput(attrs={
                'class': 'form',
                'placeholder': 'First Name',
                'type': 'text'
            }),
            "last_name": TextInput(attrs={
                'class': 'form',
                'placeholder': 'Last Name',
                'type': 'text'
            }),
            "phone_number": TextInput(attrs={
                'class': 'form',
                'placeholder': 'Phone Number',
                'type': 'text'
            }),

        }

    def clean_email(self):
        email = self.cleaned_data['email']
        if not EmailValidator()(email):
            raise forms.ValidationError('Please enter a valid email address.')
        return email

    def clean_password(self):
        password = self.cleaned_data.get('password')
        password2 = self.cleaned_data.get('password2')

        if len(password) < 8:
            raise forms.ValidationError('Password should be at least 8 characters long.')

        if password != password2:
            raise forms.ValidationError("Passwords don't match.")

        return password

    def clean_first_name(self):
        first_name = self.cleaned_data['first_name']
        if not first_name.isalpha():
            raise forms.ValidationError('First name should contain only letters.')
        return first_name

    def clean_last_name(self):
        last_name = self.cleaned_data['last_name']
        if not last_name.isalpha():
            raise forms.ValidationError('Last name should contain only letters.')
        return last_name

    def clean_phone_number(self):
        phone_number = self.cleaned_data['phone_number']
        if not RegexValidator(r'^\?\d{10,12}$', message='Please enter a valid phone number.')(phone_number):
            raise forms.ValidationError('Please enter a valid phone number.')
        return phone_number

这是 models.py 用户应用程序

import uuid
from django.db import models
from django.contrib.auth.models import User


class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    # добавляем дополнительные поля профиля пользователя и не забудьте миграцию
    email = models.EmailField(default='')
    password = models.CharField('Password', max_length=50, default='')
    password2 = models.CharField('rePassword', max_length=50, default='')
    first_name = models.CharField('Name', max_length=30, default='')
    last_name = models.CharField('Last Name', max_length=30, default='')
    phone_number = models.CharField('Number', max_length=20, default='')

    def __str__(self):
        return str(self.pk)

这是 views.py 用户应用程序

from django.shortcuts import render, redirect
from .forms import UserProfileForm



def brewtopia_view(request):
    return render(request, 'users/Brewtopia.html')


def contact_view(request):
    return render(request, 'users/Contact.html')


def handle_invalid_email(request, exception):
    return render(request, 'errors/invalid_email.html', {'error_message': str(exception)}, status=400)


def create_user(request):
    error = ''

    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        if form.is_valid():
            user_profile = form.save(commit=False)
            user_profile.user = request.user
            user_profile.save()
            return redirect('users:home')
    else:
        form = UserProfileForm()

    data = {
        'form': form
    }

    return render(request, 'users/create_user.html', data)

这是 urls.py 用户应用程序

from django.urls import path
from . import views
from .views import handle_invalid_email
from .Errors.handlers import handle_not_found, handle_server_error

app_name = 'users'

urlpatterns = [
    path('', views.brewtopia_view, name='home'),
    path('contact/', views.contact_view, name='contact'),
    path('create_user/', views.create_user, name='create_user')
]

handler404 = handle_not_found
handler500 = handle_server_error
handler400 = handle_invalid_email


create_user.html

<!DOCTYPE html>
{% load static %}
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Register</title>
    <link rel="stylesheet" href="{% static 'users/css/style_register.css' %}">
</head>

<body>
<form method="post">
    {% csrf_token %}
    <input checked="" id="signin" name="action" type="radio" value="signin">
    <label for="signin">Sign in</label>
    <input id="signup" name="action" type="radio" value="signup">
    <label for="signup">Sign up</label>
    <input id="reset" name="action" type="radio" value="reset">
    <label for="reset">Reset</label>
    <div id="wrapper">
        <div id="arrow"></div>
        {{ form.email }}
        {{ form.password }}
        {{ form.password2 }}
        {{ form.first_name }}
        {{ form.last_name }}
        {{ form.phone_number }}
        <span>{{ error }}</span>
    </div>
    <button type="submit">
    <span>
      Reset password
      <br>
      Sign in
      <br>
      Sign up
    </span>
    </button>
</form>
</body>
</html>

python django sqlite pycharm
© www.soinside.com 2019 - 2024. All rights reserved.