默认头像没有出现在我的 django 项目配置文件中

问题描述 投票:0回答:1

我尝试在我的个人资料页面中加载默认头像图像,但它没有显示。然而,新的头像照片确实如此。 解释一下,我穿了什么?

个人资料页面HTML模板:

{% extends 'movieapp/base.html' %}
{% load static %}
{% block content %}
<h1>Данные пользователя</h1>
<form  method='post' enctype="multipart/form-data">
    {% csrf_token %}
    {% if user.photo %}
         <p><img src="{{ user.photo.url }}">
    {% else %}
         <img src="{% static 'default_image' %}">
    {% endif %}
    {% for f in form %}
    <p><label class="form-label" for="{{ f.id_for_label }}">{{ f.label }}</label>{{ f }}</p>
    <div class="form-error">{{ f.errors }}</div>
    {% endfor %}
    <p><button type="submit">Отправить</button></p>

</form>

<hr>
<p><a href="{% url 'password_change'%}">Сменить пароль</a></p>
{% endblock %}

forms.py:

class ProfileUserForm(forms.ModelForm):
    username = forms.CharField(disabled='Логин', widget=forms.TextInput(attrs={'class': 'form-input'}))
    email = forms.CharField(disabled='E-mail', widget=forms.TextInput(attrs={'class': 'form-input'}))
    this_year = datetime.date.today().year
    date_birth = forms.DateField(widget=forms.SelectDateWidget(years=tuple(range(this_year - 100, this_year - 5))))
    class Meta:
        model=get_user_model()
        fields=['photo','username','email','date_of_birth','first_name','last_name',]
        labels={
            'first_name':'Имя',
            'last_name':'Фамилия',

        }
        widgets={
            'fist_name':forms.TextInput(attrs={'class': 'form-input'}),
            'last_name':forms.TextInput(attrs={'class': 'form-input'})
        }

models.py:

from django.contrib.auth.models import AbstractUser
from django.db import models

# Create your models here.
class User(AbstractUser):
    photo=models.ImageField(upload_to='users/%Y/%m/%d/',blank=True,null=True,verbose_name='Фото')
    date_of_birth=models.DateTimeField(blank=True,null=True,verbose_name='Дата рождения')

views.py:

class ProfileUser(UpdateView):
model=get_user_model()
form_class = ProfileUserForm
template_name = 'user/profile.html'
success_url = reverse_lazy("profile_changed.html")
extra_context = {'title': 'Профиль пользователя',
                 'default_image':settings.DEFAULT_USER_IMAGE}

设置.py:

STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/users/'
DEFAULT_USER_IMAGE = MEDIA_URL + 'profile/chad.jpg'

项目网址:

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('movieapp.urls')),
path("__debug__/", include("debug_toolbar.urls",namespace='users')),
path("users/", include("users.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

默认头像图片目录:

python django django-forms django-templates
1个回答
0
投票

在您的视图类中,您已经传递了 default_photo 变量。因此,在您的模板中,您应该使用 {{ default_photo }},而不是 {% static 'default_image' %}。

© www.soinside.com 2019 - 2024. All rights reserved.