python - 我放在图像字段中的默认配置文件在 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>
解决方案
因为 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中,因为图像是文件类型
推荐阅读
- cross-validation - 将 ga() 用于任何术语时的 GAMLSS CV 错误
- excel - 如何在循环中复制 500 个单元格值并运行它直到到达最后一个单元格
- tensorflow - 为什么张量流数据集需要在拟合之前进行批处理?
- javascript - 将两个日期转换为字符串并进行比较
- javascript - 如何在 javascript 中读取本地静态文件以在 html 中使用(CORS 策略已阻止从源 'null' 访问位于 '' 的 XMLHttpRequest
- excel - 如何在不使用 Excel 2019 中的正确函数/VBA/DAX 的情况下将单元格中的文本大小写从混合大小写更改为正确大小写?
- javascript - 重试异步函数出错,未处理的承诺拒绝
- linux - 在 OS 中,为什么可加载内核模块 (LKM) 不需要调用消息传递来进行通信?
- python - 没有模块名称 pmadarima
- python - 根据值拆分 DataFrame