gpt4 book ai didi

python - images/create 的 TypeError - __init__() 得到了一个意外的关键字参数 'save'

转载 作者:行者123 更新时间:2023-11-28 22:24:44 26 4
gpt4 key购买 nike

我不知道这里出了什么问题。我正在尝试将其他网站的图像保存到我的数据库中,但我在 images/create 中遇到了 TypeError - __init__() got an unexpected keyword argument 'save'。 images 是一个应用程序,create 是 url 的名称。这是代码

网址.py

from django.conf.urls import url
from . import views

urlpatterns = [
url(r'^create/$', views.image_create, name='create'),
]

View .py

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import ImageCreateForm

@login_required
def image_create(request):
if request.method == 'POST':
# Form is sent
form = ImageCreateForm(data=request.POST)
if form.is_valid():
# Form data is valid
cd = form.cleaned_data
new_item = form.save(commit=False)

# Assign current user to the item
new_item.user = request.user
new_item.save()
messages.success(request, 'Image added successfully')

# Redirect to the newly created item detail view
return redirect(new_item.get_absolute_url())
else:
# Build form with data provided by the bookmarklet via GET
form = ImageCreateForm(data=request.GET)

return render(request, 'images/image/create.html',
{'section' : 'images', 'form' : form})

以及 forms.py,其中还包含覆盖 save() 方法的代码

from urllib import request
from django import forms
from django.core.files.base import ContentFile
from django.utils.text import slugify
from .models import Image

class ImageCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = ('title', 'url', 'description')
widgets = {
'url' : forms.HiddenInput,
}

def clean_url(self):
url = self.cleaned_data['url']
valid_extensions = ['jpg', 'jpeg']
extension = url.rsplit('.', 1)[1].lower()
if extension not in valid_extensions:
raise forms.ValidationError('the given URL doesn\'t match valid image extensions')
return url

def save(self, force_insert=False, force_update=False, commit=True):
image = super(ImageCreateForm, self).save(commit=False)
image_url = self.cleaned_data['url']
image_name = '{}.{}'.format(slugify(image.title),
image_url.rsplit('.', 1)[1].lower())

# Download image from given URL
response = request.urlopen(image_url)
image.image.save(image_name, ContentFile(response.read(), save=False))

if commit:
image.save()
return image

请有人帮忙!

最佳答案

ContentFile在其 __init__ 中不使用关键字 save:

ContentFile(response.read(), save=False)
# ^^^ ????

关于python - images/create 的 TypeError - __init__() 得到了一个意外的关键字参数 'save',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46116596/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com