我正在使用React / Redux前端和Django后端进行一个小项目。除了标准的Django服务器之外,我没有使用任何东西进行开发。我正在尝试将图像字段添加到现有的UserProfile模型中。目前我已经完成了所有工作,但Django无法正确地将我的图像提供给React主站点或管理站点。当我尝试导航到相关网址或使用Python请求库直接请求媒体时,响应的类型为“text / html”。目前我的模型有以下字段:
models.py
class UserProfile(models.Model):
...
...
profile_image = models.ImageField(upload_to='path_to_media')
项目urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/account/', include('account.urls')),
url(r'^api/post/', include('post.urls')),
url(r'.*', views.root, name='root')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'nattr'),
)
帐户urls.py
urlpatterns = (
...,
url(r'^edit_profile/(?P<user_id>[^/]+)/$',
views.edit_profile,
name='edit_profile'),
)
帐户views.py
def edit_profile(request, user_id):
try:
user = User.objects.get(pk=user_id)
form = UserProfileForm(request.POST, request.FILES, instance=user.profile, user=request.user)
valid = form.is_valid()
if valid:
profile = form.save()
return JsonResponse(profile.to_user())
else:
return JsonResponse({'errors': form.errors}, status=400)
except User.DoesNotExist:
return JsonResponse({'errors': 'cannot find user with that id'}, status=400)
我做错了什么?我已经分配了media_url
&amp; media_root
;我已将媒体网址添加到urlpatterns
。我的视图和表单非常标准,我可以看到图像正在上传到文件夹结构
答案 0 :(得分:4)
按顺序处理Django URL模式。您在.*
之前有settings.MEDIA_URL
,因此无论如何,每个网址都会被它抓住。您应该将静态网址移到.*
上方。
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/account/', include('account.urls')),
url(r'^api/post/', include('post.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# make sure this is always last
urlpatterns += [url(r'.*', views.root, name='root')]
答案 1 :(得分:1)
在urlpatterns
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
并将此添加到您的settings.py
ENV_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(ENV_PATH, 'media/')
MEDIA_URL = '/media/'