gpt4 book ai didi

python - 当我提交时,图像字段在 django 中被清除

转载 作者:行者123 更新时间:2023-12-04 09:28:54 24 4
gpt4 key购买 nike

我正在尝试创建一个类似于 Instagram 的社交媒体应用程序,但是出于某种原因,当我将图片加载到图像字段并提交时,图像被清除,并说该字段是必需的。
Before submission
After submission
在 Django 中,代码为
View .py

@login_required
def new_post(request):
if request.method == 'POST':
form = CreateNewPost(request.POST)
if form.is_valid():
messages.success(request, "Post has been created")
form.save()
return redirect('home')
else:
form = CreateNewPost()
return render (request, "posts/post_form.html", {"form":form})
我暂时将默认用户保留为无,因为它坚持让我在最初创建模型时选择一个。这是这个问题的原因吗?如果是这样,我该如何摆脱它。
html代码...
    <form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Add a Post!</legend>
{{ form | crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Post</button>
</div>
</form>
模型.py
class Post(models.Model):
image = models.ImageField(upload_to='post_images')
caption = models.CharField(blank=True, max_length=254)
date_posted = models.DateTimeField(auto_now_add=timezone.now)
author = models.ForeignKey(User, on_delete = models.CASCADE)

def save(self):
super().save()
img = Image.open(self.image.path)
width, height = img.size
ratio = width/height
if img.height > 500:
outputsize = (500, (height/ratio))
img.thumbnail(outputsize)
img.save(self.image.path)
表格.py
class CreateNewPost(forms.ModelForm):
class Meta:
model = Post
fields = ["image","caption"]
以防万一,urls.py
urlpatterns = [
path('', views.home, name='home'),
path('new_post/', views.new_post, name="new_post"),
]
我也尝试过使用基于类的 View ,这给了我同样的错误

最佳答案

您需要通过 request.FILES [Django-doc]对于表单,这是一个类似字典的对象,其中包含 UploadedFile上传文件的对象:

@login_required
def new_post(request):
if request.method == 'POST':
form = CreateNewPost(request.POST, request.FILES)
if form.is_valid():
form.instance.author = request.user
form.save()
messages.success(request, 'Post has been created')
return redirect('home')
else:
form = CreateNewPost()
return render (request, 'posts/post_form.html', {'form':form})

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

关于python - 当我提交时,图像字段在 django 中被清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62917980/

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