Reputation: 31
I have been working on creating a blog sharing application using Django.I am trying to add an image field so that users will be able to upload images and view them as posts. But the image is not getting uploaded. Django is not even throwing any errors. The code is running fine but the image is not getting uploaded.
I have tried adding "enctype" in the template, as well as making the necessary changes in urls.py. I have even specified the MEDIA_ROOT and MEDIA_URL in settings.py. if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have added this in my urls.py.
My models.py
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User,
on_delete=models.CASCADE,related_name='%
(app_label)s_%(class)s_related')
picture =
models.ImageField(upload_to='images',default='default.png',null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('project-home')
My Views.py
class PostCreateView(SuccessMessageMixin,LoginRequiredMixin,CreateView):
model = Post
fields = ['title','content','picture']
success_message = 'Your submission is sucessful!'
def form_valid(self,form):
form.instance.author = self.request.user
return super().form_valid(form)
def get_success_message(self):
return self.success_message
the image is not getting uploaded. Thanks in advance!
Upvotes: 2
Views: 1505
Reputation: 1
If you are using class-based views you do something like this
class PostCreateView(CreateView):
model = Post
form_class = PostForm
template_name = 'post_create.html'
success_url = reverse_lazy('post-list')
Upvotes: 0
Reputation: 1437
in the form element add enctype="multipart/form-data"
<form method="post" enctype="multipart/form-data">
......
......
</form>
Upvotes: 3
Reputation: 160
i think you need to create a form for the Post Model and add this form to the create view [form_class =PostForm] instead of the [model=Post]
Upvotes: 0