I'm trying to create a new object in a CreateView via ModelForm. I want the 'player' instance to have a image. But the uploaded image doesn't get stored to the 'player_image'-directory or written in the DB.
These are my files:
models.py:
class Player(models.Model):
last_name = models.CharField(max_length=255, verbose_name=_("Last Name"))
first_name = models.CharField(max_length=255, verbose_name=_("First Name"))
secret_name = models.CharField(max_length=255, verbose_name=_("Secret Key"), unique=True)
image = ImageField(upload_to='player_images/', verbose_name=_("Image"), null=True, blank=True)
player_form.py
class PlayerForm(forms.ModelForm):
last_name = forms.CharField(required=True, label=_("Last Name"))
first_name = forms.CharField(required=True, label=_("First Name"))
class Meta:
model = Player
fields = ['first_name', 'last_name', 'image']
player_add_view.py
class PlayerAddView(LoginRequiredMixin, CreateView):
form_class = PlayerForm
template_name = "project/player_add_view.html"
model = Player
def form_valid(self, form):
player = form.save(commit=False)
# I do other stuff here
player.save()
return HttpResponseRedirect(reverse('home'))
I don't know why it's not working but in my project, which works, I'm getting the image from the post request like so:
profile_form = ProfileForm(data=request.POST)
if profile_form.is_valid():
if 'picture' in request.FILES:
current_user.image = request.FILES['image']
Go to your template and add:
<form method="post" enctype="multipart/form-data">
There might be something missing like request.FILES in views.py or enctype="multipart/form-data" in the form.
Look here: https://docs.djangoproject.com/en/1.8/topics/http/file-uploads/
or see this : https://godjango.com/35-upload-files/
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