P
P
PcheI12020-12-12 17:13:14
Django
PcheI1, 2020-12-12 17:13:14

Django form image not saving. What is the problem?

There is a blog application and there is a form,

class NewPostForm(forms.ModelForm):
    class Meta(object):
        model = Post
        fields = ("title", "content", "image")
        labels = {
            "content": "Text"
        }

        widgets = {
            "title": Textarea(attrs={"rows": 2, "cols": 55}),
            "content": Textarea(attrs={"rows": 30, "cols": 55})
        }
modeled
class Post(models.Model):

    title = models.CharField(null=None, max_length=100)
    content = models.CharField(null=None, blank=True, max_length=5000, default=" ")
    created_at = models.DateTimeField(auto_now_add=True)
    visible = models.BooleanField(default=True)
    author = models.CharField(max_length=100, null=False, default="test")
    image = models.ImageField(upload_to="blog", null=True, blank=True)

    def get_absolute_url(self):
        return reverse_lazy("blog:update-post", kwargs={"pk": self.pk})

    def __str__(self):
        visible = "\N{FIRE}" if self.visible else "\N{SLEEPING SYMBOL}"
        msg = f'[{self.pk}] "{self.title}" {visible}'
        return msg

    class Meta:
        ordering = ["-created_at", "title", "pk"]
The essence is very simple and lies in the fact that the data from the form is written to the database and from there it gets to the main page, but I apparently made a mistake somewhere and the picture is saved only through the admin panel.

View code
class NewPostView(LoginRequiredMixin, CreateView):

    form_class = NewPostForm
    template_name = "blog/post_form.html"
    success_url = reverse_lazy("blog:index")
    extra_context = {
        "action_name": "Create Post",
        "action_url": reverse_lazy("blog:new-post"),
    }

    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.author = self.request.user
        instance.save()
        return redirect(self.success_url)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
PcheI1, 2020-12-12
@PcheI1

I figured it out myself, the error was in html. If someone needs it, then in the form tag you need to specify the attributeenctype=multipart/form-data

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question