Django 图片不显示

Django image does not display

我是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>

我正在尝试 select 动态地添加图片,而不仅仅是添加图片的名称。 请问有人知道如何解决这个问题吗?

在您看来所有的方法都是post,没有get方法从数据库中获取数据

尝试添加 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 link 如果你想看的话。 https://github.com/RazzTazz28/Django-Atlas.git

那么,我该从哪里开始呢?我对代码做了一些修改。我post这个答案是因为也许有像我这样的初学者,不用为了20行代码在网上刷3天。 在 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)

这将在创建新用户时创建一个信号,因此现在称为 Profile 的 UserProfile 将成为 NewUser 的一个实例。我创建了 NewUser,它将自动创建一个带有主键的配置文件 table,它继承了 NewUser pk 和 ImageField。我添加了一个名为 title 的 CharField,所以 table 看起来像这样: (1,None,'Untitled.png',1) 首先是 table id, title,img, pk inherited .

然后是 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>

这里我删除了输入框,添加了一个提交按钮。 现在,当我创建用户时,它会分配一个默认的 so-called 个人资料图片,可以从网站上进行更改。 Ofc 还有很多工作要做,但这是我上面的问题所需要的。如果您知道任何其他方法可以做到这一点,那就更好了,请告诉我。非常感谢大家!