models.py:
from django.conf import settings
from django.db import models
from django.core.files import File
def upload_location(instance, filename):
location = str(instance.user.id)
return "%s/%s" %(location, filename)
class ProfilePicture(models.Model):
user = models.ForeignKey(User)
profile_picture = models.ImageField(upload_to=upload_location, null=True, blank=True)
def __unicode__(self):
return unicode(self.user.id)
forms.py:
from django import forms
from .models import ProfilePicture
class ProfileEditPicture(forms.ModelForm):
class Meta:
model = ProfilePicture
fields = [
"profile_picture"
]
views.py:
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.shortcuts import render, get_object_or_404, render_to_response
rom .forms import ProfileEditPicture
from .models import ProfilePicture
@login_required()
def profile_picture(request, id):
user = get_object_or_404(User, id=id)
title = "Profile Edit"
profile, created = Profile.objects.get_or_create(user=user)
form = ProfileEditPicture(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
context = {
"form":form,
"title":title,
"profile":profile
}
return render(request, "profile/form.html", context)
urls.py:
urlpatterns = [
...
url(r'^profile_picture/(?P<id>[\w.@+-]+)/', 'profiles.views.profile_picture', name='profile_picture'),
...
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
模板中的HTML代码是默认的django形式。
提前致谢:)
答案 0 :(得分:1)
有用的文档是"Binding uploaded files to a form"。可能如果你遵循这个,你将克服你的问题。
除此之外,在表单元素中包含此属性非常重要:
<form method="post" action="..." enctype="multipart/form-data">