当我提交图像字段时,它在 Django 中被清除
Image field gets cleared off in django when i submit it
我正在尝试创建一个类似于 Instagram 的社交媒体应用程序,但是由于某种原因,当我将图片加载到图像字段并提交时,图像被清除,并提示该字段是必需的。
Before submission
After submission
在 Django 中,代码用于
views.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})
我暂时将默认用户保留为 none,因为它坚持让我在最初创建模型时选择一个。这是这个问题的原因吗?如果是这样,我该如何摆脱它。
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>
models.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)
forms.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"),
]
我也尝试过使用基于 class 的视图,这给了我同样的错误
您需要将 request.FILES
[Django-doc] 传递给表单,这是一个类似字典的对象,其中包含上传文件的 UploadedFile
个对象:
@login_required
def new_post(request):
if request.method == 'POST':
form = CreateNewPost(request.POST<b>, request.FILES</b>)
if form.is_valid():
form<b>.instance.author = request.user</b>
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.
我正在尝试创建一个类似于 Instagram 的社交媒体应用程序,但是由于某种原因,当我将图片加载到图像字段并提交时,图像被清除,并提示该字段是必需的。
Before submission
After submission
在 Django 中,代码用于 views.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})
我暂时将默认用户保留为 none,因为它坚持让我在最初创建模型时选择一个。这是这个问题的原因吗?如果是这样,我该如何摆脱它。
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>
models.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)
forms.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"),
]
我也尝试过使用基于 class 的视图,这给了我同样的错误
您需要将 request.FILES
[Django-doc] 传递给表单,这是一个类似字典的对象,其中包含上传文件的 UploadedFile
个对象:
@login_required
def new_post(request):
if request.method == 'POST':
form = CreateNewPost(request.POST<b>, request.FILES</b>)
if form.is_valid():
form<b>.instance.author = request.user</b>
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 theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.