保存时如何设置图像路径

时间:2019-01-23 17:39:38

标签: django python-3.x

当我从表单上传图像时,它只是在数据库中保存名称,而不是保存图像并上传到路径,但是当我从数据库上传图像时,它存储得很好

urls.py

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

urlpatterns = [
    path('',include('students.urls')),
    path('admin/', admin.site.urls),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

models.py

from django.db import models

# Create your models here.

class student_registration(models.Model):

  registration_number = models.CharField(primary_key=True,max_length=100)
  student_name = models.CharField(max_length=100)
  student_father_name = models.CharField(max_length=100)
  student_image=models.FileField(default='default.jpg', upload_to='media', blank=True)

views.py

from django.shortcuts import render
from .models import student_registration
from django.contrib import messages
from django.conf import settings

# Create your views here.
  
def student_registeration(request):  
  if ("registration_no" in request.POST and "student_name" in request.POST 
  and "student_fname" in request.POST and "student_image" in request.POST):
    registration_no = request.POST["registration_no"]
    student_name = request.POST["student_name"]
    student_fname = request.POST["student_fname"]
    student_image = (settings.MEDIA_URL + request.POST["student_image"], 
                    'JPEG')
    s = student_registration(registration_no,student_name, student_fname, 
        student_image)
    s.save()
    messages.success(request, f'Your account has been created! You are now 
     able to log in')
    return render(request,'students/student_registration.html')
  else:
    return render(request, 'students/student_registration.html')
  

1 个答案:

答案 0 :(得分:0)

文件上传存储在request.FILES中而不是request.POST中。您可以用相同的方式检索它并将其分配给student_image字段:

s = student_registration(
    registration_number=registration_no,
    student_name=student_name, 
    student_father_name=student_fname, 
    student_image=request.FILES['student_image']  # Retrieve from request.FILES
)
s.save()

您还应该确保将表单设置为enctype="multipart/form-data

相关问题