我正在使用django构建博客,我成功创建了一个新帖子,但是当我尝试更新该帖子时,所有已更新但图像未更新的操作,都没有将图像上传到Posts模型中的upload_to
这是我的代码
view.py
@login_required
def UpdatePost(request, pk):
obj = get_object_or_404(Posts, id=pk)
myForm = NewPostForm(instance = obj)
if request.method == 'POST':
myForm = NewPostForm(request.POST, request.FILES, instance=request.user.profile)
response_data = {
'SType': 'danger',
'message': "An Error Occured, pls try again later"
}
title = request.POST.get('title')
content = request.POST.get('content')
category_id = request.POST.get('category')
image = request.FILES.get('image')
if myForm.is_valid():
if Posts.objects.filter(pk=pk).update(title=title, content=content, image=image, category_id=category_id, author_id=request.user.id):
response_data = {
'SType': 'success',
'message': "Saved Successfully"
}
return HttpResponse(json.dumps(response_data), content_type="application/json")
context={
'form':myForm,
'title': obj.title,
'category': Category.objects.all()
}
return render(request, 'blog/update.html', context)
update.html
<form action="." method="POST" enctype="multipart/form-data" id="PostNew__form"> {% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Update a Blog Post</legend>
<div class="form-row">
<div class="form-group col-md-8 mb-0">
{{ form.title | as_crispy_field }}
</div>
<div class="form-group col-md-4 mb-0">
{{ form.category | as_crispy_field }}
</div>
</div>
{{ form.content | as_crispy_field }}
<div class="">
{{ form.image | as_crispy_field }}
</div>
</fieldset>
<div class="form-group">
<h6 id="PostNew__show" ></h6>
<img src=" {% static 'images/ajax-loader.gif' %}" style="Display:none;" id="PostNew__img">
<button class="btn btn-outline-info float-right" type="submit" id="PostNew__submit">Update</button>
</div>
</form>
model.py
class Posts(models.Model):
title = models.CharField(max_length=100)
category = models.ForeignKey(Category, default="1", on_delete=models.CASCADE)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='blog_pics')
def __str__(self):
return self.title
forms.py
class NewPostForm(forms.ModelForm):
class Meta:
model = Posts
fields = ['title', 'category', 'content', 'image']
请问我该如何解决这个问题,在数据库中,它存储文件名,但仅存储文件名,而没有upload_to文件夹
答案 0 :(得分:1)
在Django文档中,它显示了如何通过创建Model
实例将文件上传到Model
。 queryset上的update()
方法执行的操作不同,它会缩短字段的分配,以仅执行数据库查询。因此,它实际上不会将图像文件保存到存储中。
您应该在保存之前直接分配实例的文件字段,或者只保存表单。而且,您不必查询数据库,因为您已经具有传递给表单的实例。因此,要么这样做:
obj.image = image
obj.title = form.cleaned_data['title']
...
obj.save()
或者,因为您已经拥有ModelForm,您可以执行以下操作:
form.save()
但是请注意,您实例化表单的代码是错误的:
form = NewPostForm(request.POST, request.FILES, instance=obj) # not request.user.profile
如果由于您的模型要求的字段不属于表单而无法直接保存该表单,则应使用commit=False
:
post = form.save(commit=False)
post.author = request.user # and assign other fields that are not part of the form
post.save()