0

I need some fresh eyes, what am I missing here? In my Post Model imageField is defined as "picture" to be uploaded on the site, I seed it on my admin panel, it gets uploaded just fine but I can't seem to make it appear on the page: http://127.0.0.1:8000/posts/. I get ValueError at /posts/ The 'picture' attribute has no file associated with it. Highlited line is line 257, in post_comment_create_view return render(request, 'network/posts.html', context) Model:

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

Forms:

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

Views:

@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 %}

2 Answers2

0

There should be quotes around the src:

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

Should be:

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

This is for the tag attributes. For content within the tag, what you have is fine, no quotes. This is good:

<span>{{ c.user }}</span>   <!-- works -->
raphael
  • 2,469
  • 2
  • 7
  • 19
  • Thank you, I already noticed I missed the quotes. And that's the posts view mate @R. Uziel – kingmathers92 Jan 23 '22 at 14:31
  • My bad. I should have asked for the `urls.py` to see that. But maybe the `settings.py` might help. Specifically the `MEDIA_URL` and the `MEDIA_ROOT`, and the `DEBUG` parts. Check out https://stackoverflow.com/questions/5517950/django-media-url-and-media-root. – raphael Jan 23 '22 at 14:42
  • I solved mate, I had to check if the img exists with an If statement @R. Uziel – kingmathers92 Jan 23 '22 at 14:55
0

I solved it, the solution is that I had to check if the img exists:

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