The photo is uploaded and saved in the database but I can't show the picture in the template. Now, what can I do? Where is the problem? What will be the logic?
Settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = [STATIC_DIR]
MEDIA_URL = '/media/'
Urls:
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('business_app.urls')),
] static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Views:
def change_profile_picture(request):
if request.user.is_authenticated:
if request.method == "POST":
profile_picture = request.FILES['profile_picture'] if 'profile_picture' in request.FILES else None
user = get_object_or_404(User, pk=request.user.pk)
if request.user.pk != user.pk:
return redirect("/")
Profile_picture.objects.create(
Profile_picture = profile_picture,
USer = request.user,
)
return redirect("/")
return render(request,'0_index.html')
Models:
class Profile_picture(models.Model):
USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE, related_name="user_propic")
Profile_picture = models.ImageField(upload_to="3_profile_picture/",default='3_profile_picture/avatar.png', null=True, blank=True)
templates:
<img src="static/1_images/3_about.jpg" alt="" width="100"
>
CodePudding user response:
First you have to pass your Profile_picture
object to your template like so, with new_pf
being an instance of that object:
views.py
return render(request,'your_html_page.html', {'pf': new_pf})
Then in your template your_html_page.html
:
<img src="{{ pf.Profile_picture.url }}">
In your template you are referring to your Profile_picture
instance with pf
, then accessing the Profile_picture
attribute, then accessing the built-in url
attribute to get the url which the browser will display as a picture.
CodePudding user response:
You can try in your settins.py
import os
STATIC_URL = '/static/'
STATICFILES_DIRS=[
BASE_DIR / "static"
]
MEDIA_URL="/media/"
MEDIA_ROOT=os.path.join(BASE_DIR,"media/")
in your template
<img src="{% static '1_images/3_about.jpg' %}" alt="" width="100"
>