ForeignKey不起作用django,我使用自定义用户模型,我尝试了MySQL和PostgreSQL



在我的SubUser模型中,当我添加一些子用户时,ForeignKey不起作用,它没有将主用户id添加到其user_id字段中。我尝试了所有来自堆栈溢出的解决方案,并在MySQL和PostgreSQL中都尝试过,这里是我的代码:

仪表板/型号.py

from django.db import models
from django.conf import settings
from django.contrib.auth.models import BaseUserManager
from account.models import Account
from django.contrib.auth import get_user_model
# Create your models here.

class CustomUserAdmin(BaseUserManager):
ordering = ('email',)

class SubUser(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
image = models.ImageField(null=True, blank=True)
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
fullname = models.CharField(max_length=220)
phone_number = models.CharField(max_length=100, unique=True)
address = models.CharField(max_length=220)
user_role = models.CharField(max_length=220)
def __str__(self):
return self.fullname

仪表板/视图.py

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from . import forms
from django.conf import settings

# Create your views here.
@login_required(login_url='account:index')
def dashboard(request):
return render(request, 'dashboard/table.html')

@login_required(login_url='account:index')
def add_sub_user(request):
form = forms.AddSubUserForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.save()
print(settings.AUTH_USER_MODEL)
context = {'form':form}
return render(request, 'dashboard/add_subuser.html',context)

账户/模块.py

class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=220, unique=True)
fullname = models.CharField(max_length=220)
phone_number = models.CharField(max_length=220, unique=True)
address = models.CharField(max_length=220)
date_joined = models.DateTimeField(verbose_name='data joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now_add=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
username = models.CharField(max_length=220, unique=True, blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['phone_number']
objects = MyAccountManager()
def __str__(self):
return self.fullname
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True

在settings.py中,我做了:AUTH_USER_MODEL='account.account'

提前感谢

我找到了解决方案。在仪表板/视图中.py我添加了

obj.user = request.user

现在它正在中工作

相关内容

  • 没有找到相关文章

最新更新