ImageField を介して画像をアップロードすると、フォームが無効になります。ファイルに適切にバインドする必要があることは承知していますが、不足しているものや間違っているものはわかりません。これに関するDjangoの知恵を本当に感謝します。
モデル.py
class New_User(models.Model):
user = models.OneToOneField(User, unique = True)
birthday = models.DateField(null=True)
name = models.CharField(max_length=100)
image = models.ManyToManyField(Image)
album = models.ManyToManyField(Album)
avatar = models.ImageField("Profile Pic", upload_to='images/', blank =True, null=True)
def __unicode__(self):
return unicode (self.user)
**forms.py**
class Upload(ModelForm):
class Meta:
model = New_User
**Views.py**
@login_required
def Profile(request):
#if not logged in, we send them to the log in page
if not request.user.is_authenticated():
return HttpResponseRedirect('/login')
user_reg = request.user.get_profile()
'''Saving the profile pic'''
if request.method =="POST":
picture_form = Upload(request.POST, request.FILES, instance = user_reg)
if picture_form.is_valid():
avatar = form.cleaned_data['avatar']
a = New_User(avatar = avatar)
a.save()
#resize and save image under same filename
#save_file(request.FILES['avatar'])
return HttpResponse('Thanks for uploading the image')#just to test if the image is valid
else:
return HttpResponse('Fail')#just to test if the image is not valid
else:
picture_form = Upload(instance = user_reg)
if user_reg.avatar:
image = "/media/" + user_reg.avatar.name
context = {"user_reg" : user_reg, "picture_form" : picture_form, "image":image, "media_url": MEDIA_URL}
return render_to_response("profile.html", context, context_instance= RequestContext(request))
def save_file(file, path =''):
'''Save file function'''
filename = file._get_name()
fd = open("%s/ %s" % (MEDIA_ROOT, str(path) + 'images/' + str(filename)), 'wb')
for chunk in file.chunks():
fd.write(chunk)
fd.close()
**Profile.html**
<div class='row'>
<div class="span">
<form enctype="multipart/form-data" action="/profile" method="POST">
{% csrf_token %}
<div style='float:left;'>
<p>{{ picture_form.avatar }}</p>
<input type="submit" value="Submit" id="submit" />
</form>