无法使用 imageField 在我的 Django 社交应用程序上显示图片?

Can't display picture on my django social app using imageField?

我需要一些新鲜的眼光,我在这里缺少什么?在我的 Post 模型 imageField 中被定义为要上传到网站上的“图片”,我将它播种在我的管理面板上,它上传得很好,但我似乎无法让它出现在页面上:http://127.0.0.1:8000/posts/。我在 /posts/ 得到 ValueError 'picture' 属性没有与之关联的文件。突出显示的行是 post_comment_create_view 中的第 257 行 return 渲染(请求,'network/posts.html',上下文) 型号:

class Post(models.Model):
    # id is created automatically by Django
    picture = models.ImageField(upload_to='images', blank=True, validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])])
    content = models.TextField()
    liked = models.ManyToManyField(Profile, blank=True, related_name="likes")
    author = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-created',)

    def __str__ (self):
        return str(self.content[:20])

表格:

class PostModelForm(forms.ModelForm):
    content = forms.CharField(widget=forms.Textarea(attrs={'rows':2}))
    class Meta:
        model = Post
        fields = ('content', 'picture')

观看次数:

@login_required
def post_comment_create_view(request):
    qs = Post.objects.all()
    profile = Profile.objects.get(user=request.user)

    #Setting up pagination
    p = Paginator(qs, 5)
    page = request.GET.get('page')
    post_list = p.get_page(page)

    #Post form, comment form
    p_form = PostModelForm()
    c_form = CommentModelForm()
    post_added = False

    profile = Profile.objects.get(user=request.user)

    if 'submit_pForm' in request.POST:
        print(request.POST)
        p_form = PostModelForm(request.POST, request.FILES)
        if p_form.is_valid():
            instance = p_form.save(commit=False)
            instance.author = profile
            instance.save()
            p_form = PostModelForm()
            post_added = True

    if 'submit_cForm' in request.POST:
        c_form = CommentModelForm(request.POST)
        if c_form.is_valid():
            instance = c_form.save(commit=False)
            instance.user = profile
            instance.post = Post.objects.get(id=request.POST.get('post_id'))
            instance.save()
            c_form = CommentModelForm()

    context = {
        'qs': qs,
        'profile': profile,
        'p_form': p_form,
        'c_form': c_form,
        'post_added': post_added,
        'post_list': post_list,
    }

    return render(request, 'network/posts.html', context)

HTML:

{% block body %}
<div>
    <div class="border border-light rounded" style="width: 25rem;">
        {% if post_added %}
            <div id="alertFade" class="alert alert-success" role="alert">Post added!</div>
        {% endif %}
        <form action="" method="POST" enctype="multipart/form-data" class="form-group">
            {% csrf_token %}
            {{p_form}}
            <button type="submit" class="btn btn-sm btn-success" name="submit_pForm">Send Post</button>
        </form>
    </div>
    {% for obj in post_list %}
        <div class="card center" style="width: 30rem;">
            <div class="card-head" style="background-color: #d0e2bc;">
                <img width="50px" class="avatar img-thumbnail rounded-circle z-depth-2 ml-1" src={{obj.author.avatar.url}}> {{ obj.author.user }} - {{ obj.created|naturaltime }}
                {% if request.user == obj.author.user %}
                    <a href="{% url 'post-delete' obj.pk %}"><button class="btn btn-sm btn-success float-right mt-2 mr-1">Delete</button></a>
                    <a href="{% url 'post-update' obj.pk %}"><button class="btn btn-sm btn-success float-right mr-1 mt-2">Edit</button></a>
                {% endif %}
            </div>
            <div class="card-body">
                <img src={{obj.picture.url}}> <br>
                <p class="card-text">{{obj.content|safe}}</p>
                <hr>
            </div>
            <button class="cmt_btn ui button mb-5">show / hide comments</button>
            <div class="comment-box">
            {% if obj.comment_set.all %}
                {% for c in obj.comment_set.all %}

                    <img width="20px" class="avatar img-thumbnail rounded-circle"src={{c.user.avatar.url}} alt="">
                    <span>{{ c.user }}</span>
                    <div class="mt-2">{{ c.body }}</div>

                {% endfor %}
            {% endif %}

src 应该有引号:

<img src={{obj.picture.url}}>   <!-- will not work -->

应该是:

<img src="{{obj.picture.url}}">   <!-- works -->

这是针对标签属性的。对于标签中的内容,您所拥有的很好,没有引号。这很好:

<span>{{ c.user }}</span>   <!-- works -->

我解决了,解决办法是我必须检查img是否存在:

{% if obj.picture %}
    <img src="{{obj.picture.url}}"> <br/>
{% endif %}