I was create a profile for user. I done set up all the Media and Static. But when I set default and upload_to in image field, it error not found image. I had try all the different Path image but it doesn't work either. Can someone check the path for me. Thank a lot !
path in setting:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/images')
MEDIA_URL = '/media/'
url project:
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.IndexPage.as_view(),name='index'),
path('welcome/',views.WelcomePage.as_view(),name='welcome'),
path('bye/',views.ByePage.as_view(),name='bye'),
path('about/',views.AboutPage.as_view(),name='about'),
path('profile/', include('accounts.urls'))
]
if settings.DEBUG:
urlpatterns = static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
model:
class UserInfoCnc(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(upload_to = 'profile_pics', default='profile_pics/xinlacho.JPG' ,blank=True
forms.py:
class UserDetailForm(forms.ModelForm):
class Meta:
model = UserInfoCnc
fields = ('user', 'about', 'face_site', 'ins_site', 'profile_pic')
views.py:
class UserDetailView(DetailView):
form_class = forms.UserDetailForm
model = models.UserInfoCnc
template_name = 'userinfocnc_detail.html'
show image in html:
<img class='img-thumbnail' src="{{ userinfocnc.profile_pic.url }}" alt="Error load image">
file media and static in project:
CodePudding user response:
I think if there is no image it should be set to null=True, with that you can validate if there is an image with 2 options:
Option 1
<img src=“{{ object.image.url|default:'/media/default_avatar.jpg' }}">
Option 2
{% if object.image %}
<img src="{{ object.image.url }}">
{% else %}
<img src="{% static 'default_avatar.jpg' %}">
{% endif %}
CodePudding user response:
So, the images file was serving files uploaded by a user and the default images was save in media folder. All you need to do it change the STATIC to MEDIA.
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And if you use UpdateView to change the images of user. You must add enctype="multipart/form-data"
in <form action="" method="post" enctype="multipart/form-data" >
and the UpdateView will handle the rest.