问题是图像没有保存.当我选择图像和上传所有的代码工作正常,但图像不保存django



问题是图像没有保存。当我选择一个图像并上传所有正常工作的代码,但图像不保存。我逐行检查了所有的代码,我不明白是什么问题。我还看到媒体文件,无论图像是否保存,但图像没有保存。

这是models.py在这个文件中我使用了image字段models.py

class Answer (models.Model):
question=models.ForeignKey(Question,on_delete=models.CASCADE)
user=models.ForeignKey(User,on_delete=models.CASCADE, null=True)
img=models.ImageField(null=True,blank=True,upload_to='Answer_Img')
detail=RichTextUploadingField()
add_time=models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.detail

forms.py

class AnswerForm(ModelForm):
class Meta:
model=Answer
fields=('detail','img')
labels={'img':'Upload Image'}

views.py

def answer(request,pk,slug):
try:
trend=Question.objects.get(pk=pk,slug=slug)
except:
raise Http404("Post Does Not Exist")
tags=trend.tags.split(',')  
ans=Answer.objects.filter(question=trend)
answerform=AnswerForm
if request.method=='POST':
answerData=AnswerForm(request.POST)
if answerData.is_valid():
answer=answerData.save(commit=False)
answer.question=trend
answer.user=request.user
answer.save()
p=messages.success(request,'Answer has been submitted.')
return HttpResponseRedirect(trend.slug)

return render(request,"ask/answer.html" ,{
'trends':trend,
'tags':tags,
'answer':ans,
'form':answerform,

})

answer.html

{% if user.is_authenticated %}
<div class="container">
<div class="py-5 text-center bg-secondary text-white">
<h1 class="mb-3">Upload Image</h1>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form}} 
<input type="submit" class="btn btn-danger" value="Upload">
</form>
</div>
{% else %}
<h3><P>Sign In/Sign Up before posting answers</P></h3>
<h4><li><a href="{% url 'account_login' %}" class=" text-left text-info">Sign In</a></li><h4>
<h4> <li><a href="{% url 'account_signup' %}" class=" text-left text-info">Sign Up</a></li><h4>
{% endif %}

settings.py

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

urls . py

urlpatterns = [
# my url patterns here
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

使用请求。文件获取img。请检查媒体文件夹是否在您的基本目录中,并且子文件夹名称是否正确。

if request.method == "POST":

answer_form = Answer_form(data=request.POST)
if(answer_form.is_valid()):
ans = answer_form.save(commit=False)
#ans.user = user

if 'img' in request.FILES:
ans.img = request.FILES['img']

ans.save()

else:
print(answer_form.errors)

这是文档页面:

文件上传

相关内容

  • 没有找到相关文章

最新更新