图像没有存储在Django的媒体文件夹中,但数据库包含图像名称

问题描述 投票:0回答:1

views.py

  employee = Employee.objects.create(
user=request.user,  # Assigning the current user
first_name=request.POST.get('employee_firstname'),
middle_name=request.POST.get('employee_middlename'),
last_name=request.POST.get('employee_lastname'),
email=request.POST.get('employee_email'),
land_phone_number=request.POST.get('employee_landphone'),
mobile_phone_number=request.POST.get('employee_mobile'),
gender=request.POST.get('gender'),
hire_date=request.POST.get('hire_date'),
position=position,
address=address,
date_of_birth=request.POST.get('dob'),
img=request.FILES.get('imgg'),  # Make sure you're using request.FILES for image files

模型.py

class Employee(models.Model):
img = models.ImageField(upload_to='pics')

设置.py

    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),

]

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

`#定义媒体URL

`MEDIA_URL = '/media/'

url.py

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

add_user.html

<div class="contact-img">
<input type="file" id="imgg" name="imgg" class="form-control" accept="image/*">

列表.html

<img src="{{ datas.employee.img.url }}" alt="User Avatar" class="user-avatar">

“为什么它没有存储在媒体/图片文件夹中?”

html django image file jinja2
1个回答
0
投票

像这样更新views.py后现在可以工作了

img_file = request.FILES.get('imgg')
     try:
     employee = Employee.objects.create(
     img=img_file


 employee.save()  # This should trigger the print/log statements

列表.html

{% if datas.employee.img %}
            <img src="{{ datas.employee.img.url }}" alt="User Avatar" class="user-avatar">
        {% else %}
            <img src="{% static 'path/to/default/image.png' %}" alt="Default Avatar" class="user-avatar">
        {% endif %}

enter code here
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.