我是Django的新手,基本上是在这里编程,我在使这个简单的应用程序一切正常时,当我尝试在该用户名旁边显示个人资料图片时,从管理员页面保存了已注册用户帐户的个人资料图片时,显示空白,但显示用户名和电子邮件,我不知道我做错了什么,任何帮助将不胜感激。...
models.py
from django.db import models
from django.contrib.auth.models import User
class profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg',upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} profile'
settings.py
STATIC_URL = '/static/'
#Media root will be full directory where we want django to store uploaded files
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
#crispy to use bootstrap4
CRISPY_TEMPLATE_PACK = 'bootstrap4'
LOGIN_REDIRECT_URL = 'blog-home'
LOGIN_URL = 'login'
profile.html在我的模板内
{% extends "blog/base.html"%}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
</div>
</div>
</div>
{% endblock content%}
urls.py
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from users import views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/',user_views.register,name='register'),
path('profile/',user_views.profile,name='profile'),
path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'),
path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'),
path('',include('blog.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
注意:
users uploaded pic will be saved on django_project -> media ->profile_pics->pics.jpg
views.py
from django.shortcuts import render,redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request,f'Your Account had been created now you are able to login')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html',{'form':form})
@login_required
def profile(request):
return render(request,'users/profile.html')
答案 0 :(得分:0)
将/ media /放入img src
<img class="rounded-circle account-img" src="/media/{{ user.profile.image }}">
答案 1 :(得分:0)
您的图像需要枕头库才能与Django一起使用。您可以使用pip
进行安装,如下所示:
pip install Pillow
然后,您应将其导入models.py
中,如下所示:
from PIL import Image