首页 > 解决方案 > 我放在图像字段中的默认配置文件在 Django 中不起作用

问题描述

我有一个自定义用户模型,它有一个图像字段,我还添加了一个默认选项并提供了一个默认选项,但用户似乎并没有在我将其渲染到模板上时使用默认选项。

我观察到,只有当我在其上添加图像时,它才能工作,但如果其中没有图像,它不会使用默认值。

这是文件结构/目录,以防我在那里犯了一些错误 在此处输入图像描述

设置.py

STATIC_URL = 'static/'
STATIC_ROOT = 'staticfiles/'
STATICFILES_DIRS = [BASE_DIR / 'static']

MEDIA_URL = 'media/'
MEDIA_ROOT = 'media/'

网址.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('admin/', admin.site.urls),
    path('', include('core.urls'))
]

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

模型.py

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=254, unique=True)

    # CUSTOM USER FIELDS
    firstname = models.CharField(max_length=30)
    lastname = models.CharField(max_length=30)
    image = models.ImageField(upload_to='images/users', blank=True, null=True, default='images/users/profile-pixs.png')

视图.py

def Register(request):
    title = "Create a new Account"

    if request.user.is_authenticated:
        return redirect('/')

    elif request.method == 'POST':
        firstname = request.POST.get('firstname')
        lastname = request.POST.get('lastname')
        telephone = request.POST.get('telephone')
        country = request.POST.get('country')
        email = request.POST.get('email')
        image = request.POST.get('image')
        password1 = request.POST.get('password1')
        password2 = request.POST.get('password2')

        user = User.objects.create_user(firstname=firstname, password=password1, 
            email=email, lastname=lastname, telephone=telephone, country=country, image=image)
        user.save()
        messages.success(request, "You have successfully created an account")
        return redirect('login')

    return render(request, 'auth/register.html', {"title":title})

模板.html

<div class="image">
    <a href="#">
        <img src="{{request.user.image.url}}" alt="John Doe" />
    </a>
</div>

标签: pythondjangodjango-modelsdjango-viewsdjango-templates

解决方案


因为 django 在你的媒体目录中寻找你的默认图像,而我可以看到你的默认图像在静态目录中,将图像从静态复制并粘贴到媒体

    firstname = models.CharField(max_length=30)
    lastname = models.CharField(max_length=30)
    image = models.ImageField(upload_to='images/users', default='profile-pixs.png')

那么您可能想知道为什么它将文件保存在该目录中,因为您还加载了静态目录的 urlpattern

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

删除它然后你可以看到你也不能从你身边添加配置文件,也可以将你的照片保存目录移动到媒体目录以获取干净的代码,如果你想要默认照片,还可以删除 null 和空白,因为那样它就没有意义了并且在通过请求方法请求任何文件时,django 在您的媒体目录中查找该文件,是的也使用

request.FILES['image']

在您的views.py中,因为图像是文件类型


推荐阅读