I have a form where I am supposed to upload an image, but I can't get the image to save. Everything else in the form works properly except the image.
I'm sure there are some issues with my addGame
method, but I've tried it dozens of different ways with no luck.
I've gone through the documentation , but it appears I'm still doing something wrong, as the image never gets saved.
(Just as a side note: I'm using Pillow for cropping the image, and I'm not sure if I'm doing that properly either, but I just added that in recently, and since the image doesn't save I have no way of knowing whether that is implemented correctly. I'm leaving the cropping part commented out while I try to get the upload to work.)
forms.py
class GameForm(forms.ModelForm):
image = forms.ImageField()
code = forms.Textarea()
deleteGame = forms.BooleanField(required=False, widget=forms.HiddenInput())
class Meta:
model = Game
fields = ('title', 'image', 'description', 'requirements', 'code', 'deleteGame')
views.py
:
@login_required
def add_game(request):
user = request.user
if request.method == 'POST':
form = GameForm(request.POST, request.FILES)
if form.is_valid():
form = form.save(commit=False)
image = request.FILES['image']
box = (200, 200, 200, 200)
cropped = image.crop(box)
form.image = cropped
form.user = request.user
form.save()
return HttpResponseRedirect('/userprofile')
else:
form = GameForm()
args = {}
args.update(csrf(request))
args['user'] = user
args['form'] = form
return render_to_response('addgame.html', args)
models.py
class Game(models.Model):
user = models.ForeignKey(User, blank=True)
title = models.CharField(max_length=256)
image = models.ImageField(upload_to='games', blank=True)
description = models.CharField(max_length=256)
requirements = models.CharField(max_length=256)
code = models.TextField()
deleteGame = models.BooleanField(default=False)
def __unicode__(self):
return self.title
My media settings look like this:
MEDIA_ROOT = 'media/'
MEDIA_URL = '/media/'
File Structure:
If I add an image via the admin portal, it saves properly, but I get an error like this in my log:
Not Found: /media/games/Screen_Shot_2015-12-29_at_1.03.05_AM.png
如果您打算将文件与表单数据一起发送,则模板中的form
标记需要enctype="multipart/form-data"
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.