Python 如何在Django框架中正确地将图像显示到html模板?
我已经尝试了一天,试图将保存到媒体文件夹中的图像显示在我的模板文件中,但没有成功。图像已上载到媒体/图像文件夹,但我不知道如何显示它们。我不知道我做错了什么,因为我看到很多人使用这些方法并得到了结果。我在想也许我的post函数没有将正确的数据返回到模板? 我对Django和html非常陌生,所以请原谅我的错误 这是我当前的设置: 设置.pyPython 如何在Django框架中正确地将图像显示到html模板?,python,html,django,imagefield,filefield,Python,Html,Django,Imagefield,Filefield,我已经尝试了一天,试图将保存到媒体文件夹中的图像显示在我的模板文件中,但没有成功。图像已上载到媒体/图像文件夹,但我不知道如何显示它们。我不知道我做错了什么,因为我看到很多人使用这些方法并得到了结果。我在想也许我的post函数没有将正确的数据返回到模板? 我对Django和html非常陌生,所以请原谅我的错误 这是我当前的设置: 设置.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models.py
from django.db import models
class Post(models.Model):
post = models.ImageField(upload_to="images")
forms.py
from django import forms
from imageDetection.models import Post
class HomeForm(forms.ModelForm):
class Meta:
model = Post
fields = ('post',)
views.py
class HomeView(TemplateView):
template_name = 'imageDetection/test.html'
@staticmethod
def detect(request):
return render(request, 'imageDetection/detection.html')
def get(self, request):
form = forms.HomeForm()
return render(request, self.template_name, {'form': form})
def post (self, request):
context = {}
if request.method == "POST":
form = forms.HomeForm(request.POST, request.FILES)
if form.is_valid():
image_form = models.Post()
image_form.post = form.cleaned_data['post']
image_form.save()
context['form'] = image_form
return render (request, 'imageDetection/detection.html', context)
else:
form = forms.HomeForm()
context['form'] = form
return render(request, self.template_name, context)
url.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('imageDetection.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
模板/Detection.html
{% for post in form %}
{% if post.image %}
<img src="{{ MEDIA_URL }}{{ post.image.url }}" />
{% endif %}
{% endfor %}
{%以%的形式发布]
{%if post.image%}
{%endif%}
{%endfor%}
谢谢,如果您有任何帮助,我们将不胜感激。在此,我在您的模型中没有看到任何名为
image
的字段。您已使用字段名post
定义了图像
{% if post.post %}
<img src="{{ post.post.url }}" />
{% endif %}
{%if post.post%}
{%endif%}
在这里,最好为字段和上下文使用有意义的变量。您可以使用
image
来命名图像字段,而不是post
,使用contextimages
来命名图像字段,而不是forms
让我们来解决这个问题。如果你通过django管理员添加一个新帖子(带有图片),你能看到图片吗?当你从你的主页视图添加一篇新文章时,你能在管理员中看到图片吗?谢谢,这很有效!!我第一次试的时候一定是做错了什么。