Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'))
like image 538
Dominic Avatar asked Sep 06 '15 11:09

Dominic


3 Answers

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']
like image 79
dietbacon Avatar answered Nov 09 '22 02:11

dietbacon


Go to your template and add:

 <form method="post" enctype="multipart/form-data">
like image 35
Alexis Avatar answered Nov 09 '22 02:11

Alexis


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/

like image 39
Shekhar Singh Choudhary Avatar answered Nov 09 '22 03:11

Shekhar Singh Choudhary