skip to Main Content

I created a post form and embedded with the template and view as usual, when I test the form and try to create a new post all the fields process and save the data correct to the object except the image object. It does not prompt me an error, it is like ignoring completely the file that I upload.

The post model:

from django.db import models

from User.models import User


class Post(models.Model):
    author = models.ForeignKey(User, related_name="post", on_delete=models.CASCADE)
    title = models.CharField(max_length=280)
    content = models.CharField(max_length=500)
    post_image = models.ImageField(upload_to="post_images/", blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

The form class:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'content', 'post_image']



The post_create view:

def create_post(request):
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            author = request.user
            title = form.cleaned_data['title']
            content = form.cleaned_data['content']
            post_image = form.cleaned_data['post_image']
            post = Post.objects.create(author=author, title=title, content=content, post_image=post_image)
            return redirect("home")

    form = PostForm()

    return render(request=request, template_name="post/create_post.html", context={"form": form})

The create_post.html

{% extends "base/base.html" %}

{% block content %}
<form method="POST" action="{% url 'create_post' %}">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Create Post</button>
</form>

{% endblock %}

The urls:

from django.urls import path

from . import views

urlpatterns = [
    path("create_post", views.create_post, name="create_post")
]

When I create the post throuht the creat_post template the image field results empty, But when I upload the image through the admin panel it works perfeclt well.

2

Answers


  1. You are not passing files to your form, which is why it is unable to find your image file and not uploading it.

    You can change your post_create view to upload your image file.

    Try this:

    def create_post(request):
        if request.method == 'POST':
            form = PostForm(request.POST, request.FILES)  # -----> here add request.FILES
            if form.is_valid():
                author = request.user
                title = form.cleaned_data['title']
                content = form.cleaned_data['content']
                post_image = form.cleaned_data['post_image']
                post = Post.objects.create(author=author, title=title, content=content, post_image=post_image)
                return redirect("home")
    
        form = PostForm()
    
        return render(request=request, template_name="post/create_post.html", context={"form": form})
    
    Login or Signup to reply.
  2. In addition to what Divya mentioned, you also need to add enctype="multipart/form-data" to the form:

    <form method="POST" enctype="multipart/form-data" action="{% url 'create_post' %}">
      {% csrf_token %}
      {{ form.as_p }}
       <button type="submit">Create Post</button>
    </form>
    

    This allows for file and image uploads.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search