当前位置: 首页 > 面试题库 >

Django-TypeError-save()得到了意外的关键字参数'force_insert'

戴鸿羽
2023-03-14
问题内容

我是Django的新手,我无法弄清楚这个错误。请帮忙。它提供了TypeError-
save()得到了意外的关键字参数’force_insert’。我测试了下面的代码,他们能够保存新的用户注册,但现在将不再保存…

这是我认为有问题的views.py的一部分:

    from django.shortcuts import render, redirect
    from django.contrib.auth.forms import UserCreationForm
    from django.contrib import messages
    from django.contrib.auth.decorators import login_required
    from . forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm

    def register(request):
        if request.method == 'POST':
            form = UserRegisterForm(request.POST)
            if form.is_valid():
            username = form.cleaned_data.get('username')
            form.save(force_insert=False)
            messages.success(request, f'Thank you {username}! Your account has been created!')
            return redirect('login')
    else:
        form = UserRegisterForm()

    return render(request, 'users/register.html', {'form':form})

和models.py

from django.db import models
from django.contrib.auth.models import User
from PIL import Image

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics')

    def __str__(self):
        return (self.user)

    def save(self):
        super().save()

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300,300)
            img.thumbnail(output_size)
            img.save(self.image.path)'

问题答案:

当您在Django中覆盖模型的save方法时,还应该传递*args**kwargs覆盖方法。该代码可能工作正常:

def save(self, *args, **kwargs):
    super(Profile, self).save(*args, **kwargs)

    img = Image.open(self.image.path)

    if img.height > 300 or img.width > 300:
        output_size = (300,300)
        img.thumbnail(output_size)
        img.save(self.image.path)'


 类似资料: