Sascha Wick
Sascha Wick

Reputation: 65

How to let a User upload an image in Django

Hi Guys

I started coding in Django and i just wanted to make an 9gag-Clone. I followed some Tutorials and acctualy made a Blog. But when i "upload" Images it allways take the default value.

So here is my Html:

{% extends "posts/post_base.html" %}
{% load bootstrap3 %}
{% block post_content %}
    <h3 class="title">Poste Some Memes here</h3>
    <form action="{% url 'posts:create' %}" method="POST">
        {% csrf_token %}
        {% bootstrap_form form %}
        <input type="submit" value="posten" class="btn btn-primary btn-large">
    </form>
{% endblock %}

Here is my Views.py:

class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView):
    fields = ('title','picture','group')
    model = models.Post

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save()

        return super().form_valid(form)

and at least my models.py:

class Post(models.Model):

    user = models.ForeignKey(User,related_name='posts')
    created_at = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=30,default='Titel')
    picture= models.ImageField(upload_to=settings.MEDIA_ROOT, default='/static/img/default.png')
    title_html = models.CharField(max_length=30,default='Titel', editable = False)
    group = models.ForeignKey(Group,related_name='posts',null=True,blank=True)

    def __str__(self):
        return self.title

    def save(self,*args,**kwargs):
        self.title_html =misaka.html(self.title)
        super().save(*args,**kwargs)


    def get_absolute_url(self):
        return reverse('posts:single',kwargs={'username':self.user.username,'pk':self.pk})

    class Meta:
        ordering = ['-created_at']
        #unique_together = ['user','title','bild']

urls.py and other htmlfiles work correctly. everything was makemigrated and migrated

I just need to know why it dont save the Images, or dont upload it.

Upvotes: 1

Views: 3401

Answers (3)

Sascha Wick
Sascha Wick

Reputation: 65

Both answers where right so couldn't pick them bouth. So here is the solution:

Added

enctype="multipart/form-data" 

to my HTML-Form

AND

added

self.bild = self.request.FILES['bild']

to my CreatePost

Upvotes: 0

Somil
Somil

Reputation: 1941

Just replace

<form action="{% url 'posts:create' %}" method="POST">

with

 <form action="{% url 'posts:create' %}" method="POST"   enctype="multipart/form-data>

Upvotes: 2

Roshan Shrestha
Roshan Shrestha

Reputation: 441

Uploaded image are at self.request.FILES

self.object.picture = self.request.FILES or self.request.FILES.get('key')
self.object.save()

You can POST data in self.request.POST and file in self.request.FILES

Upvotes: 1

Related Questions