首页 > 解决方案 > django - 数据库中预设的数据,但无法通过 Model.objects.all()/Admin 查看

问题描述

我正在尝试为已使用电子邮件、电话号码等注册的用户保存个人资料详细信息。

我的表单成功提交并根据需要重定向到个人资料页面。配置文件数据在模板中可见,例如{{request.user.profile.dob}}

但是,当我访问 /admin 页面并浏览时/admin/profiles/profile/,它会显示0 profiles

当我通过 shell 运行 Profile.objects.all() 时,它给出了<QuerySet []>.

但是,当我通过 User 对象之一访问配置文件时,我得到了数据。当我使用查询通过 sqlite 控制台检查时,配置文件数据存在select * from profiles_profile;

我很生气,但我认为这一定是我的一个明显错误。

请帮忙。

谢谢


这是我的模型

/users

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=254, unique=True, help_text="A verification link will be sent to this email-id")
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    mobile = models.CharField(db_index=True,max_length=10,null=True, verbose_name="mobile number",)
    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'

/profiles
class Profile(models.Model):
    user=models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
    primary_key=True, related_name="profile")
    name=models.CharField(max_length=70, null=True)
    dob=models.DateField(blank=False,null=True, verbose_name="Date of birth",); 

设置.py

AUTH_USER_MODEL = 'users.User'

这是我的模型表单

class PersonalDetailsForm(forms.ModelForm):

    class Meta:
        model=Profile
        fields=('name', 'dob', )

和 CreateView

class AddPersonalDetails(CreateView, ):
    model=Profile
    form_class=PersonalDetailsForm
    def form_valid(self, form):

        profile = form.save(commit=False)
        profile.user = self.request.user
        profile.save()
        return redirect(reverse('my_profile'))

提交表格后,

标签: djangodjango-admin

解决方案


推荐阅读