【问题标题】:Image/Files not Being Posted Django图像/文件未发布 Django
【发布时间】: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 和媒体根配置。

标签: python django image


【解决方案1】:

在您的表单标签中,您必须添加 enctype="multipart/form-data" 并且您必须在模板中包含 {{form.media}} 如果您想将任何类型的文件发布到 Django。

<form method = "POST" action = "." enctype="multipart/form-data">

 {% csrf_token %}
 
 {{form.media}}
 
 <div class="form-group">

   {{form|crispy }}

 </div>

 <button type = "submit" class = "btn btn-primary">Done</button>

</form>

【讨论】:

    猜你喜欢
    • 2021-04-11
    • 2015-05-02
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多