【问题标题】:How to save a django model to database? save() method is not working如何将 django 模型保存到数据库? save() 方法不起作用
【发布时间】:2021-01-25 21:49:52
【问题描述】:

您好,我无法将 django 模型保存到我的数据库中。

我的应用程序使用 Google 登录进行身份验证,如果身份验证后用户的个人资料不在数据库中,它会将他们重定向到可以创建个人资料的表单。

问题是每当用户创建配置文件时,它都不会保存到数据库中。

下面我附上了我的管理页面的图片。 (你会看到没有 Profile 对象) 我还附上了我的 forms.py、models.py 和 views.py

views.py

def register(request):

user_email = Profile.objects.filter(email = request.user.email).exists()
if request.user.is_authenticated:
    if user_email:
        return redirect('blog-home')
    else:
        if request.method == 'POST':
            profile = Profile()
            profile_form = CreateProfileForm(request.POST, instance=profile)
            if profile_form.is_valid():
                profile.user = request.user
                profile.email = request.user.email
                profile_form.save()
                messages.success(request, f'Your account has been created! You are now able to log in')
                return redirect('blog-home')
        else:
            profile_form = CreateProfileForm()

    context = { 'form': profile_form  }

return render(request, 'users/register.html', context)

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, null = True, on_delete=models.CASCADE)
    username = models.CharField(max_length = 15, default = '')
    first_name = models.CharField(max_length=20, default='')
    last_name = models.CharField(max_length=20, default='')
    email = models.CharField(max_length = 25, default = '')
    #image = models.ImageField(null=True, blank=True, upload_to='media/user/profile')
    #interests

    def __str__(self):
        return f'{self.first_name} Profile'

forms.py

class CreateProfileForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = ['first_name', 'last_name', 'username']

【问题讨论】:

    标签: python django django-models django-views django-forms


    【解决方案1】:

    看起来您好像混淆了 profile 和 profile_form 并因此覆盖了您的更改。您应该调用 profile.save() 而不是 profile_form.save(),因为您已经对配置文件进行了更改(添加用户和电子邮件)。无需在 is_valid() 方法中实例化新的 Profile()。试试这样的:

    if request.method == 'POST':
        profile_form = CreateProfileForm(request.POST)
        if profile_form.is_valid():
            profile = profile_form.save(commit=False)
            profile.user = request.user
            profile.email = request.user.email
            profile.save()
            messages.success(request, f'Your account has been created! You are now able to log in')
            return redirect('blog-home')
    

    【讨论】:

    • 你说的很有道理。但是,当我尝试它时,我最终还是和以前一样。当我进入我的 Python shell 时,这很奇怪,它显示了所有正在创建的对象。由于某种原因,它只是没有显示在管理数据库中
    • 哦,我想我知道问题出在哪里了!我从来没有将我的模型导入到我的 admin.py 文件中大声笑
    • 是的,它现在可以工作了。我忘记将我的个人资料模型注册到我的 admin.py 文件中。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 2013-05-11
    • 2017-10-11
    • 2014-01-30
    • 2017-01-16
    • 2016-07-07
    相关资源
    最近更新 更多