0
我有一個個人資料頁面,我希望允許用戶上傳個人資料圖片。我可以編輯所有文字,但無法上傳圖像。如果我通過管理員添加圖片,但無法通過網站上的用戶個人資料頁面,它就可以工作。請注意,通過管理員創建時,它會正確上傳到我在媒體文件夾中指定的目錄(profile_image)。我在模板頁面上創建了一些錯誤處理,但是生成的錯誤是這樣的:「'image'屬性沒有與它關聯的文件。」下面是我的代碼:無法在Django上傳圖片
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
first_name = models.CharField(default='',max_length=100)
last_name = models.CharField(default='',max_length=100)
email = models.CharField(max_length=100, default='')
date_birth = models.DateField(default=datetime.datetime.now())
bio = models.TextField(default='')
image = models.ImageField(upload_to='profile_image', blank=True)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
views.py
@login_required
def edit_profile(request):
profile = get_object_or_404(models.UserProfile)
if request.method == 'POST':
form = forms.EditProfileForm(data=request.POST, instance=profile)
if form.is_valid():
form.save()
return redirect('/accounts/profile')
else:
form = forms.EditProfileForm(instance=profile)
args = {'form':form}
return render(request, 'accounts/edit_profile.html', args)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
from . import models
class UserProfileForm(forms.ModelForm):
class Meta:
model = models.UserProfile
fields = [
'first_name',
'last_name',
'email',
'date_birth',
'bio',
'image',
]
class EditProfileForm(UserProfileForm):
model = models.UserProfile
fields = [
'first_name',
'last_name',
'email',
'date_birth',
'bio',
'image',
]
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'accounts/media')
edit_profile.html
{% extends "layout.html" %}
{% block title %}User Profile | {{ user }}{{ super }}{% endblock %}
{% block body %}
<h1>My Profile</h1>
<form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p}}
<button type="submit">Save</button>
</form>
{% endblock %}
是 - 就是這樣。謝謝你 - 一個很大的幫助。 –