Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageField() not saving images in ModelForm - Django/Python

When I try to upload a picture from my form, everything processes, but the image is not being saved.

Does anyone know why this is happening?

Thanks ahead of time!

models.py:

class Photo(models.Model):
    user = models.ForeignKey(MyUser, null=False, blank=False)
    category = models.ForeignKey("Category", default=1, null=True, blank=True)
    title = models.CharField(max_length=30, null=True, blank=True)
    description = models.TextField(max_length=120, null=True, blank=True)
    image = models.ImageField(upload_to='user/photos/', null=True, blank=True)
    slug = models.SlugField(null=True, blank=True)
    active = models.BooleanField(default=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)

    class Meta:
        unique_together = ('slug', 'category')
        ordering = ['-timestamp']

    def __unicode__(self):
        return "%s" %(self.user)

views.py:

def photo_upload_view(request, username):
    u = MyUser.objects.get(username=username)

    if request.method == 'POST':
        form = PhotoUploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request, "Thank you! You have successfully posted your picture!")
            return HttpResponseRedirect('/')
    else:
        form = PhotoUploadForm()

    submit_btn = "Upload Post"

    context = {
        "form": form,
        "submit_btn": submit_btn
    }
    return render(request, "photos/photo_upload.html", context)

forms.py:

class PhotoUploadForm(forms.ModelForm):

    class Meta:
        model = Photo
        fields = ('user', 'category', 'title', 'description', 'image')

.html:

<form method='POST' action='{{ action_url }}'>{% csrf_token %}
    {{ form|crispy }}
    <input class='btn btn-default {{ submit_btn_class }}' type='submit' value='{{ submit_btn }}'/>
</form>
like image 685
jph Avatar asked Mar 20 '15 16:03

jph


People also ask

Can we store images in Django database?

We can now proceed and define a model that shall be used to store the images in our app. In Django, a default database is automatically created for you. All you have to do is add the tables called models. The upload_to tells Django to store the photo in a directory called pics under the media directory.

What is Modelform in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.


2 Answers

You should add the enctype=multipart/form-data attribute to the <form> tag:

<form method='POST' action='{{ action_url }}' enctype='multipart/form-data'>
like image 184
catavaran Avatar answered Oct 11 '22 21:10

catavaran


except for adding enctype=multipart/form-data, another possible reason that your image is not saving in modelform can be adding request.FILES in your POST condition:

if request.method == 'POST':
    form = forms.ProjectCreateForm(request.POST, instance=project)

should be:

if request.method == 'POST':
    form = forms.ProjectCreateForm(request.POST, request.FILES, instance=project)
like image 1
Weilory Avatar answered Oct 11 '22 20:10

Weilory