在几个小时后尝试更新views.py中的ImageField,我需要你的帮助:
模特:
class ImageTeam(models.Model):
image = models.ImageField(upload_to="imageTeam/", null=False)
team = models.OneToOneField(Team,on_delete=models.CASCADE,related_name="theImage", null=False)
查看:
def update_team(request, idTeam):
try :
team = Team.objects.get(id = idTeam)
except Team.DoesNotExist :
return redirect(teams)
...
if request.method == "POST" :
form = updateTeamForm(request.POST, request.FILES)
if form.is_valid() and form.has_changed() :
team.name = form.cleaned_data["name"]
...
imageForm = form.cleaned_data["image"]
if imageForm :
if hasattr(team, 'theImage') :
team.theImage.image = imageForm
print(team.theImage.image) #Good it prints "<ImageFieldFile: imageName.jpg>"
team.theImage.save() #save doesn't works!
print(team.theImage.image) #Bad it prints "<ImageFieldFile: None>"
else :
#works!
ImageTeam.objects.create(image = imageForm, team=team)
...
模板:
<form method="POST" enctype="multipart/form-data" action="{% url 'update_team' team.id %}" class="form-signin">
{% csrf_token %}
...
<div class="row">
{{ form.image }}
</div>
...
FORM:
class updateTeamForm(forms.ModelForm):
image = forms.ImageField(widget=forms.ClearableFileInput(attrs={'id':'image_team'}))
...
class Meta :
model = Team
exclude = ['image',...]
我尝试了很多解决方案(获取实例并保存,使用request.FILES [&#39; image&#39;],直接在路径中写入...)
那么为什么imageField没有更新? 如果我今天能解决这个问题,我将非常高兴
答案 0 :(得分:1)
我认为这里的问题是imageForm = form.cleaned_data["name"]
。 ImageForm不是&#39; image&#39;。如果要存储文件,则需要获取该文件。
form.cleaned_data['image']
就是你需要的。此外,我没有看到任何表单字段name
,因此请确保保存不起作用。
此外,调试这些场景的好方法是使用像ipdb这样的调试器。只需将import ipdb; ipdb.set_trace()
放在函数的顶部,然后在执行期间逐步执行代码。
希望这有帮助!