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>
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.
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.
You should add the enctype=multipart/form-data
attribute to the <form>
tag:
<form method='POST' action='{{ action_url }}' enctype='multipart/form-data'>
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With