为什么图像没有保存在django的媒体目录中



我正在尝试将图像保存在media/images目录中,并完成了下面描述的每个必要步骤。但毕竟,我的目录中没有图像,请有人指导我问题出在哪里。非常感谢。

型号.py

from django.db import models
# Create your models here.
class students(models.Model):
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
fathername = models.CharField(max_length=50)
city = models.CharField(max_length=50)
country = models.CharField(max_length=50)
state = models.CharField(max_length=50)
zip = models.IntegerField(blank=True)
address = models.CharField(max_length=100)
contact =models.CharField(max_length=20)
photo = models.ImageField(upload_to='images/', height_field=None, width_field=None, max_length=None)

urls.py

from django.urls import path, include
from home import views
from django.contrib import admin
from home import StudentViews
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
path("", views.index, name="index"),
path("Add_Student", views.Add_Student, name="Add_Student"),
path("display_students", views.Display_Student, name="display_students"),
path("<int:id>", views.student_profile, name="student_profile"),
#path("student/<int:id>/view", views.student_profile, name="student_profile"),
path("Student_Home", StudentViews.StudentHome, name="Student_Home")

]
#this line is for media 
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

设置.py

在settings.py中,我添加了以下代码行。

MEDIA_ROOT= os.path.join(BASE_DIR, 'media/images')
MEDIA_URL= "/images/"

我的目录

学生_管理_系统

  • 主页
  • 媒体/图像
  • 模板
  • 静态的

注意:我已经安装了枕头。

视图.py

以下是我的视图Add_Student,它将条目添加到数据库中。

from django.shortcuts import render, redirect
from home.models import students
# Create your views here.
def index(request):
return render(request, "index.html")
def Add_Student(request):
if request.method == 'POST':
firstname = request.POST.get('firstname')
lastname = request.POST['lastname']
fathername = request.POST['fathername']
city = request.POST['city']
country = request.POST['country']
state = request.POST['state']
zipcode = request.POST['zip']
address = request.POST['address']
contact = request.POST['contact']
photo = request.POST['photo']
Add_Student = students.objects.create(firstname=firstname, lastname=lastname, fathername=fathername, city=city,country=country, state=state, zip=zipcode, address=address, contact=contact, photo=photo)
Add_Student.save()
return redirect('Add_Student')
else:
return render(request, 'student/Add_Student.html')

更新您的MEDIA_ROOT

MEDIA_ROOT= os.path.join(BASE_DIR, 'your_app_name/media')

您可以阅读文档point number 2

定义upload_to选项指定要用于上载文件的MEDIA_ROOT的子目录。

此外,请确保已将文档中提到的enctype="multipart/form-data"表单属性添加到模板中

注意这个请求。如果请求方法是POST并且发布请求的方法具有属性enctype=",则FILES将仅包含数据;多部分/形式数据";。否则,请求。FILES将为空。

Add_student视图也有一点变化

photo = request.FILES['photo']
Add_Student.save() # NO need to use this. create() creates and saves the object at the same time.

你可以在这里阅读

最新更新