Dominic
Dominic

Reputation: 317

Django Create View Image Upload

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'))

Upvotes: 11

Views: 12854

Answers (3)

Alexis
Alexis

Reputation: 25163

Go to your template and add:

 <form method="post" enctype="multipart/form-data">

Upvotes: 27

Shekhar Singh Choudhary
Shekhar Singh Choudhary

Reputation: 1712

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/

Upvotes: 26

Fabio
Fabio

Reputation: 3067

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']

Upvotes: 2

Related Questions