【发布时间】:2021-05-08 17:31:23
【问题描述】:
我一直在尝试在 Django 中发布图像,但我不知道为什么没有发布它们。我使用 image = form.cleaned_data.get("image") 并且它没有被保存。每当我保存图像时都不会保存但文本或内容会被保存,现在我很困惑。请帮帮我...
模型.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length = 200)
content = models.TextField()
image = models.ImageField(upload_to = "post_img", null = True, blank = True)
pub_date = models.DateTimeField(default = timezone.now)
author = models.ForeignKey(User, on_delete = models.CASCADE)
def __str__(self):
return f"{self.title} // {self.author}"
forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "content", "image"]
Views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import Post
from .forms import PostForm
# Create your views here.
def index(request):
posts=Post.objects.order_by("-pub_date")
context ={
"posts":posts
}
return render(request, "index.html",context)
def post_view(request):
form = PostForm(request.POST,request.FILES or None)
if form.is_valid():
title = form.cleaned_data["title"]
content = form.cleaned_data["content"]
image = form.cleaned_data.get("image")
activeUser = request.user
post = Post.objects.create(title = title, content = content, image = image, author = activeUser)
post.save()
return redirect("posts:home")
else:
form = PostForm()
return render(request, "post.html", {"form": form})
post.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<form method = "POST" action = ".">
{% csrf_token %}
<div class="form-group">
{{form|crispy }}
</div>
<button type = "submit" class = "btn btn-primary">Done</button>
</form>
{% endblock content %}
我已选择图片并发布,但我的图片仍不会保存在数据库中 [
【问题讨论】:
-
Hello @Aakash Thapa 尝试打印
form.cleaned_data.get("image")检查它是否正在获取文件以及是否正在获取文件,而不是提供您的媒体 URL 和媒体根配置。