Python Django 和 SQLite3 注册问题

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

我在将客户条目保存到 CustomerProfile 表时遇到问题。它似乎保存在用户表上,但不保存在客户配置文件表上。我有两个名为 app 和 user 的文件夹。

这是我的代码。

来自应用程序的表格

from django import forms
from django.contrib.auth.forms import UserCreationForm
from user.models import Customer, CustomerProfile, generate_customer_id


class Customer_Register_Form(UserCreationForm):
    cus_name = forms.CharField(
        label="Customer Name", widget=forms.TextInput(attrs={"class": "form-control"})
    )
    email = forms.EmailField(widget=forms.EmailInput(attrs={"class": "form-control"}))
    phone_number = forms.CharField(
        widget=forms.TextInput(attrs={"class": "form-control"})
    )
    address = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"}))

    username = forms.CharField(
        widget=forms.TextInput(
            attrs={"class": "form-control", "placeholder": "Enter your username"}
        )
    )
    password1 = forms.CharField(
        label="Password",
        widget=forms.PasswordInput(
            attrs={"class": "form-control", "placeholder": "Enter your password"}
        ),
    )
    password2 = forms.CharField(
        label="Confirm Password",
        widget=forms.PasswordInput(
            attrs={"class": "form-control", "placeholder": "Confirm your password"}
        ),
    )

    class Meta:
        model = Customer  # Use your custom user model
        fields = [
            "username",
            "cus_name",
            "password1",
            "password2",
            "email",
            "phone_number",
            "address",
        ]

    def save(self, commit=True):
        user = super().save(commit=False)
        user.cus_name = self.cleaned_data['cus_name']
        user.email = self.cleaned_data['email']
        user.phone_num = self.cleaned_data['phone_number']
        user.address = self.cleaned_data['address']
        
        if commit:
            user.save()
            # Assuming there's a one-to-one relationship between User and CustomerProfile
            CustomerProfile.objects.create(username=user, cus_id=generate_customer_id(user))

        return user

来自用户的模型

from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db.models.signals import post_save
from phonenumber_field.modelfields import PhoneNumberField
from django.dispatch import receiver

# Create your models here.


class User(AbstractUser):
    class Role(models.TextChoices):
        CUSTOMER = "CUSTOMER", "Customer"
        PHARMACIST = "PHARMACIST", "Pharmacist"
        RETAILASSISTANT = "RETAILASSISTANT", "Retail Assistant"
        MANAGER = "MANAGER", "Manager"

    base_role = Role.CUSTOMER

    role = models.CharField(max_length=50, choices=Role.choices)

    def save(self, *args, **kwargs):
        if not self.pk:
            self.role = self.base_role
            return super().save(*args, **kwargs)


def generate_customer_id(instance):
    return f"CUS{instance.id:04d}"


def generate_pharmacist_id(instance):
    return f"PM{instance.id:04d}"


def generate_retail_assistant_id(instance):
    return f"RA{instance.id:04d}"


def generate_manager_id(instance):
    return f"M{instance.id:04d}"


class CustomerManager(BaseUserManager):
    def get_queryset(self, *args, **kwargs):
        result = super().get_queryset(*args, **kwargs)
        return result.filter(role=User.Role.CUSTOMER)


class Customer(User):
    base_role = User.Role.CUSTOMER

    customer = CustomerManager()

    class Meta:
        proxy = True

    def welcome(self):
        return "Only for customers"


class CustomerProfile(models.Model):
    username = models.OneToOneField(User, on_delete=models.CASCADE)
    password = models.CharField(max_length=16)
    cus_id = models.CharField(max_length=7, unique=True)
    cus_name = models.CharField(max_length=50)
    email = models.EmailField(max_length=50)
    phone_num = PhoneNumberField(blank=True, null=True)
    address = models.CharField(max_length=255, blank=True, null=True)


@receiver(post_save, sender=Customer)
def create_user_profile(sender, instance, created, **kwargs):
    if created and instance.role == "CUSTOMER":
        CustomerProfile.objects.create(
            username=instance, cus_id=generate_customer_id(instance)
        )


class PharmacistManager(BaseUserManager):
    def get_queryset(self, *args, **kwargs):
        result = super().get_queryset(*args, **kwargs)
        return result.filter(role=User.Role.PHARMACIST)


class Pharmacist(User):
    base_role = User.Role.PHARMACIST

    pharmacist = PharmacistManager()

    class Meta:
        proxy = True

    def welcome(self):
        return "Only for pharmacists"


class PharmacistProfile(models.Model):
    username = models.OneToOneField(User, on_delete=models.CASCADE)
    password = models.CharField(max_length=16)
    pharmacist_id = models.CharField(max_length=6, unique=True)


@receiver(post_save, sender=Pharmacist)
def create_pharmacist_profile(sender, instance, created, **kwargs):
    if created and instance.role == "PHARMACIST":
        PharmacistProfile.objects.create(
            username=instance, pharmacist_id=f"PM{instance.id:04d}"
        )


class RetailAssistantManager(BaseUserManager):
    def get_queryset(self, *args, **kwargs):
        result = super().get_queryset(*args, **kwargs)
        return result.filter(role=User.Role.RETAILASSISTANT)


class RetailAssistant(User):
    base_role = User.Role.RETAILASSISTANT

    RetailAssistant = RetailAssistantManager()

    class Meta:
        proxy = True

    def welcome(self):
        return "Only for retail assistants"


class RetailAssistantProfile(models.Model):
    username = models.OneToOneField(User, on_delete=models.CASCADE)
    password = models.CharField(max_length=16)
    retailassistant_id = models.CharField(max_length=6, unique=True)


@receiver(post_save, sender=RetailAssistant)
def create_retail_assistant_profile(sender, instance, created, **kwargs):
    if created and instance.role == "RETAILASSISTANT":
        RetailAssistantProfile.objects.create(
            username=instance, retailassistant_id=f"RA{instance.id:04d}"
        )


class ManagerManager(BaseUserManager):
    def get_queryset(self, *args, **kwargs):
        result = super().get_queryset(*args, **kwargs)
        return result.filter(role=User.Role.MANAGER)


class Manager(User):
    base_role = User.Role.MANAGER

    manager = ManagerManager()

    class Meta:
        proxy = True

    def welcome(self):
        return "Only for managers"


class ManagerProfile(models.Model):
    username = models.OneToOneField(User, on_delete=models.CASCADE)
    password = models.CharField(max_length=16)
    manager_id = models.CharField(max_length=5, unique=True)


@receiver(post_save, sender=Manager)
def create_manager_profile(sender, instance, created, **kwargs):
    if created and instance.role == "MANAGER":
        ManagerProfile.objects.create(
            username=instance, manager_id=f"M{instance.id:04d}"
        )

请告诉我如何解决它。我不是在寻找直接的答案。谢谢你

python sql django sqlite
1个回答
0
投票

是的,因为 UserCreationForm 是 User 类的 ModelForm,可以使用“AUTH_USER_MODEL”设置参数(默认为 django.contrib.auth.models.AbstractUser)找到它,并且它只能是项目中的一个类。

要解决您的问题,您必须为

CustomerProfile
创建一个新的表单类,即 ModelForm。

© www.soinside.com 2019 - 2024. All rights reserved.