Home > other >  Django image does not display
Django image does not display

Time:04-15

I'm new to Django, and I encounter this problem with images that I can't solve... The path is like this: Django-Project, Profiles, static, media, profileIMG.

Here is my model.

    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 function

    @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)

And my template profiles.html.

    {% load static %}
    <div >
            <form method="POST" enctype="multipart/form-data">
                {% csrf_token %}
                <img  src="{{ request.user.UserProfile.profile_pic.url         
    }}"/>
                <p>This is profile page </p>
                <span>Hello, {{request.user}} </span>
                <p>{{ form }}</p>
                <input  type="submit" name="imgBTN">
                <span><a href="{% url 'logout' %}">Logout</a></span>
            </form>
        </div>

I'm trying to select an image dynamically, not just adding the name of the picture. Does anyone know how to fix this, please?

CodePudding user response:

This is what I get. I get a bit of spacing between navbar and This is profile page paragraph.

I use python manage.py runserver, and I also used / after profileIMG, not working. Also, when I submit an image, it doesn't get saved to the location.

CodePudding user response:

in your views all of method is post, nothing get method to get data from database

try add profile = UserProfile.object.get()

and then add context 'profile':profile

so the full view.py like this

    @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)

good luck and keep coding

  • Related