我正在从一本名为“Django By Example'”的最受推荐和有益的书中学习Django。有一个名为Bookmark的项目。我现在卡在表单部分,用于下载图像并将图像对象保存到数据库。我可以理解验证部分(clean_url)并下载部分。我无法进入传入save()
的参数save(self,force_insert = False,force_update = False,commit = True)
并保存图像对象
image.image.save(image_name,ContentFile(response.read()),save = False)
在此函数中使用了force_insert和force_update在哪里?
另外我不理解image.image.save()中的参数部分,因为图像有标题,网址,描述,图像等字段。是什么image_name引用?我认为response.read()部分是针对图像领域的。
有人可以让我说清楚吗?
以下是代码
class Image(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='images_created')
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, blank=True)
url = models.URLField()
image = models.ImageField(upload_to='images/%Y/%m/%d')
description = models.TextField(blank=True)
created = models.DateTimeField(auto_now_add=True,
db_index=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='images_liked',
blank=True)
views.py
def image_create(request):
"""
View for creating an Image using the JavaScript Bookmarklet.
"""
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 new 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
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 does not 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 the given URL
response = request.urlopen(image_url)
image.image.save(image_name,
ContentFile(response.read()),
save=False)
print('image',image)
if commit:
image.save()
return image
更新
要创建图像,我必须使用此网址localhost:8000 / images / create /?title = title for image& url = http://www.demo.com/image/image.jpg
答案 0 :(得分:2)
image = super(ImageCreateForm, self).save(commit=False)
在本声明中,我们将超函数分配给变量图像。
使用ImageCreateForm调用super方法。然后使用super()方法返回任何内容,我们使用commit = False调用forms.ModelForm的save()方法。
现在,如果您查看模型图像,您将找到“image”属性,该属性属于models.ImageField
为了便于理解,让我将模型的“图像”属性重命名为“image_of_model”
ImageField有一个方法保存表单
save(name,content, save)
image.image.save(image_name,
ContentFile(response.read()),
save=False)
根据我给出的术语,上述陈述变为。
image.image_of_model.save(image_name,
ContentFile(response.read()),
save=False)
我希望这可以解决你的困惑。