个人资料图片未显示在 django 模板库 html 页面中

Profile picture is not getting displayed in django template base html page

我正在创建一个 taskToDo 网络应用程序。模板下的大多数 html 文件都是 extending base.html 文件,其中包含一个导航栏,我想在其中显示 base.html导航栏下的用户头像。 个人资料图片正在 'media' 文件夹的 profile_pics 目录下保存。

我已经尝试将 {{user.profile_pic.url}} 作为图像的来源,但图像仍然没有链接 我的models.py,项目urls.py,settings.py,views.py的相关部分如下:-

models.py

from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.core.exceptions import ValidationError
from datetime import datetime
# Create your models here.

class UserCustom(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)

    profile_pic=models.ImageField(upload_to='profile_pics',blank=True)

    def __str__(self):
        return self.user.username   #user os object defined above


class UserTask(models.Model):
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    label=models.CharField(max_length=264)
    date=models.DateField()
    status=models.BooleanField(default=False)


    def __str__(self):
        return str(self.label)

settings.py

from django.contrib import admin
from django.urls import path,include
from taskApp import views
from django.conf.urls.static import static
from django.conf import settings # new
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index,name='index'),
    path('taskApp/',include('taskApp.urls')),
    path('logout/',views.user_logout,name='logout'),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

forms.py

from django import forms
from django.forms.fields import DateField
from django.core import validators
from django.contrib.auth.models import User
from taskApp.models import UserCustom,UserTask
from django.contrib.admin.widgets import AdminDateWidget
from datetime import datetime,timedelta

class UserForm(forms.ModelForm):
    password=forms.CharField(widget=forms.PasswordInput())

    class Meta():
        model=User
        fields=('username','email','password')

class UserCustomForm(forms.ModelForm):
    class Meta():
        model=UserCustom
        fields=('profile_pic',)


class UserTaskForm(forms.ModelForm):
    date=DateField(widget=forms.DateInput(attrs={'placeholder': 'YYYY-MM-DD', 'required': 'required'}))
    status=forms.BooleanField(required=False)
    class Meta():
        model=UserTask
        fields=('label','date')

    def clean(self):
        cleaned_data=self.cleaned_data
        date2=cleaned_data.get('date')
        if str(date2)<=(datetime.today()-timedelta(days=1)).strftime('%Y-%m-%d'):
            raise forms.ValidationError("The date cannot be in the past!")
        return cleaned_data

views.py(相关部分)

@login_required
def my_task(request):
    task_obj=UserTask.objects.filter(author=request.user)
    return render(request,'taskApp/task.html',{'task_obj':task_obj,'user_key':request.user})

def 注册(请求):

registered=False

if request.method == "POST":

    user_form=UserForm(data=request.POST)
    profile_form=UserCustomForm(data=request.POST)

    if user_form.is_valid() and profile_form.is_valid():
        user=user_form.save()
        user.set_password(user.password)
        user.save()

        profile=profile_form.save(commit=False)
        profile.user=user

        if 'profile_pic' in request.FILES:
            profile.profile_pic=request.FILES['profile_pic']

        profile.save()
        registered=True

    else:
        print(user_form.errors,profile_form.errors)

else: #no request=POST yet
    user_form=UserForm()
    profile_form=UserCustomForm()

return render(request,'taskApp/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered })


def register(request):
    registered=False

    if request.method == "POST":

        user_form=UserForm(data=request.POST)
        profile_form=UserCustomForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user=user_form.save()
            user.set_password(user.password)
            user.save()

            profile=profile_form.save(commit=False)
            profile.user=user

            if 'profile_pic' in request.FILES:
                profile.profile_pic=request.FILES['profile_pic']

            profile.save()
            registered=True

        else:
            print(user_form.errors,profile_form.errors)

    else: #no request=POST yet
        user_form=UserForm()
        profile_form=UserCustomForm()

    return render(request,'taskApp/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered })



def user_login(request):

    if request.method=='POST':
        username=request.POST.get('username')  #name of element
        password=request.POST.get('password')

        user=authenticate(username=username,password=password)

        if user:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect(reverse('taskApp:myTask')) #myTask is the name of url , go to urls.py
            else:
                return HttpResponse("ACCOUNT NOT ACTIVE")

        else:
            print("Someone tried to login and failed!")
            print("Username: {} and password {}".format(username,password))
            return HttpResponse("invalid login details supllied!")

    else:
        return render(request,'taskApp/login.html',{})

base.html

<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">



    <link rel="stylesheet" href="{% static 'css/mystyle.css' %}" >

    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.min.js" crossorigin="anonymous"></script> -->

  </head>
  <body>
    <nav class="navbar navbar-default navbar-static-top">
      <div class="container">

        <ul class="nav navbar-nav">
          <li><a class="navbar-brand" href="{% url 'index' %}"><em>ToDoList</em><img src={% static "images/1567073.png" %} width="60" height="50" alt="TASK_TO_DO"></a></li>
          <!-- <li><a class="navbar-brand" href="{% url 'index' %}">Task to do</a></li> -->
          <li><a class="navbar-link" href="{% url 'admin:index' %}">Admin</a></li>
        </ul>

        <ul class="nav navbar-nav">
          {% if user.is_authenticated %}
            <li><a class="navbar-link" href="{% url 'taskApp:myTask' %}">My Tasks</a></li>
            <li><a class="navbar-link" href="{% url 'taskApp:addTask' %}">Add Task</a></li>

        </ul>

        <ul class="nav navbar-nav navbar-right">
              <li><a class="navbar-link" href="#"> {{user}} <span class="glyphicon glyphicon-user"></span></a></li>
              <img class="rounded-circle article-img" src="{{user.profile_pic.url}}" width='240' alt={{user}}> <!--PROBLEM IS HERE-->
              <li><a class="navbar-link" href="{% url 'logout' %}">Logout</a></li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
        {% else %}
            <li><a class="navbar-link" href="{% url 'taskApp:register' %}">Register</a></li>
            <li><a class="navbar-link" href="{% url 'taskApp:user_login' %}">Login</a></li>
        {% endif %}
        </ul>


      </div>

    </nav>

    <div class="container">

      {% block body_block %}
      {% endblock %}


  </body>
</html>

您在什么地方使用了 UserCustomForm?在您的 views.py 中没有与此表单相关的用于将图像传递给数据库的信息。我会考虑,因为你现在正尝试在管理面板上添加图像。

在您的 html 文件中,您无法直接从用户访问 profile_pic。试试这个 src="{{user.usercustom.profile_pic.url}}"

from django.core.files.storage import FileSystemStorage 将此添加到 views.py

的顶部

并用这个编辑寄存器函数中的相关行

image = request.FILES['profile_pic']
if image:
    filename = FileSystemStorage().save('profile_pics/' + image.name, image)
    profile.profile_pic = filename
profile.save()

编辑:image =request.FILES['profile_pic] 不是字符串,尽管我们必须将它作为字符串传递给数据库。 image.name 是我们需要的字符串,但没有 MEDIA_ROOT 值。 FileSystemStorage 将 MEDIA_ROOT 值附加到它保存的任何文件