files/images in django - upload and view

 In django we can work with files, first let’s make a project and upload an image inside that . 


home/views.py/addfan()

def add_fan_page(request):

    if request.method == "POST":

        data = request.POST

        Name = data.get("name")

        Email = data.get("email")

        Profile = request.FILES.get("profile")


        # print(str(Name)+' '+str(Email)+' '+str(Profile))

        Fans.objects.create(

            name = Name,

            email = Email,

            profileimg = Profile

        )


        print("record saved!")    


    else:

        print("sorry!")    

    return render(request,"pages/addfan.html")



def all_fans_page(request):

    data = Fans.objects.all()

    print(data)

    context = { "fan":data }

    return render(request,"pages/allfans.html",context)

Note: if you want to show/display an image on django app’s url like: http://localhost:8000/profiles/brian2.jpg . So you need to set MEDIA_URL and MEDIA_ROOT path inside your django app. 


So it would looks like: you_app/urls.py

from django.conf.urls.static import static

from django.conf import settings

from django.urls import path


urlpatterns = [

    path('',home_page),

    

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


Let’s see home/templates/allfans.html

<img src="{{x.profileimg.url}}" alt="">

Note: when you want to get the url of that image object, use .url


Popular posts from this blog

MCSL 216 MCA NEW Practical ~ common questions suggestions

dev chaeatsheet

STRAPI