简体   繁体   中英

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.

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

Just replace

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

with

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM