Изображение Django не отображается
Я новичок в Django, и я столкнулся с проблемой с изображениями, которую не могу решить... Путь выглядит следующим образом: Django-Project, Profiles, static, media, profileIMG.
Вот моя модель.
from django.db import models
from accounts.models import NewUser
class UserProfile(models.Model):
user = models.OneToOneField(NewUser, on_delete=models.CASCADE)
profile_pic = models.ImageField(default='Untitled.png', upload_to='profileIMG')
def __str__(self):
return self.user.username
settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
urls.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('accounts.urls')),
path('', include('profiles.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
form.py
from django.forms import ModelForm
from .models import UserProfile
class ProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = '__all__'
exclude = ['user']
функцияview.py
@login_required(login_url='login_user')
def profiles(request):
indexID = request.user
form = ProfileForm(instance=indexID)
if request.method == 'POST':
form = ProfileForm(request.POST, request.FILES, instance=indexID)
if form.is_valid():
messages.success(request, ("The file is valid"))
form.save()
else:
messages.success(request, ("Invalid File."))
context = {'form': form}
return render(request, "profiles/profiles.html", context)
И мой шаблон profiles.html.
{% load static %}
<div class="main">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<img class="profile-pic" src="{{ request.user.UserProfile.profile_pic.url
}}"/>
<p>This is profile page </p>
<span>Hello, {{request.user}} </span>
<p>{{ form }}</p>
<input class="imgBTN" type="submit" name="imgBTN">
<span><a href="{% url 'logout' %}">Logout</a></span>
</form>
</div>
Я пытаюсь выбрать изображение динамически, а не просто добавить название картинки. Кто-нибудь знает, как это исправить, пожалуйста?
Я использую python manage.py runserver, и я также использовал / после profileIMG, не работает. Также, когда я отправляю изображение, оно не сохраняется в местоположение.
в ваших представлениях все методы являются post, нет метода get для получения данных из базы данных
try add profile = UserProfile.object.get()
и затем добавить контекст 'profile':profile
поэтому полный view.py выглядит так
@login_required(login_url='login_user')
def profiles(request):
indexID = request.user
profile = UserProfile.object.get(user=indexID)
form = ProfileForm(instance=indexID)
if request.method == 'POST':
form = ProfileForm(request.POST, request.FILES, instance=indexID)
if form.is_valid():
messages.success(request, ("The file is valid"))
form.save()
else:
messages.success(request, ("Invalid File."))
context = {'form': form, 'profile':profile}
return render(request, "profiles/profiles.html", context)
удачи и продолжайте кодировать
Вот ссылка на GitHub на весь проект, если вы хотите взглянуть. https://github.com/RazzTazz28/Django-Atlas.git
Итак, с чего мне начать? Я сделал некоторые изменения в коде. Я размещаю этот ответ, потому что, возможно, есть новичок вроде меня, которому не нужно 3 дня перелопачивать интернет ради 20 строк кода. В models.py я добавил:
class Profile(models.Model):
objects = models.Manager()
relation = models.OneToOneField(NewUser, on_delete=models.CASCADE, related_name='profile')
title = models.CharField(max_length=100, blank=True, null=True)
avatar = models.ImageField(default='profileIMG/Untitled.png', upload_to='profileIMG/', blank=False, null=False)
# L1 Signal from NewUser to instantiate Profile model
# L2 dictionary **kwargs signal when a NewUser is created
# L3 create Profile instance
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = Profile.objects.create(relation=kwargs['instance'])
# Create Profile instance of NewUser
post_save.connect(create_profile, sender=NewUser)
Это создаст сигнал, когда будет создан новый пользователь, поэтому UserProfile, который теперь называется Profile, станет экземпляром NewUser. Когда я создам NewUser, он автоматически создаст таблицу Profile с первичным ключом, который наследует NewUser pk, и ImageField. Я добавил поле CharField под названием title, так что таблица выглядит следующим образом: (1,None,'Untitled.png',1) сначала создается таблица id, title, img, pk наследуются.
Потом идет forms.py, где мало что происходит.
class ProfileForm(ModelForm):
class Meta:
model = Profile
#fields = '__all__'
exclude = ['relation', 'title']
В views.py я провел большую часть своего времени.
@login_required(login_url='login_user')
def profiles(request):
# logged in user
user = request.user
# instance id of current logged in user
instance_id = request.user.profile.id
# Profile is a instance of NewUser class
form = ProfileForm(instance=user)
if request.method == 'POST':
# form data + Profile instance
form = ProfileForm(request.POST, request.FILES, instance=user)
if form.is_valid():
# the picture that is currently uploaded by user
uploaded_file = request.FILES['avatar']
# django file system storage, we call it, so we can save the file on disk
fs = FileSystemStorage()
# we save the file. We need the name and the content of the file.
fs.save(uploaded_file.name, uploaded_file)
# new picture cleaned data from form post
avatar = form.cleaned_data.get('avatar')
#name_extension = avatar.name
#name, extension = name_extension.split(".")
#raise ValueError(avatar)
# title cleaned data from form post
title = form.cleaned_data.get('title')
# we update the database with the name of the picture we want to display
Profile.objects.filter(id=instance_id).update(avatar=avatar, title=title)
else:
messages.success(request, "Invalid File.")
context = {'form': form}
return render(request, "profiles/profiles.html", context)
А в profiles.html
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p>This is profile page </p>
<span>Hello, {{request.user}} </span>
<button class="button" name="submit_button" type="submit">Submit</button>
<p>{{ form }}</p>
<img class="avatar" src="{{ user.profile.avatar.url }}"/>
<span><a href="{% url 'logout' %}">Logout</a></span>
</form>
Здесь я удалил поле ввода и добавил кнопку отправки. Теперь, когда я создаю пользователя, он назначает так называемое изображение профиля по умолчанию, которое можно изменить на сайте. Конечно, есть еще много работы, но это то, что мне нужно для моего вопроса выше. Если вы знаете какой-либо другой способ сделать это, который лучше, пожалуйста, дайте мне знать. Большое спасибо всем!
