我已经通过使用model.py中的ImageField从管理面板成功上传了图像,但是在模板中看不到效果。请查看下面的代码和屏幕截图。在此先感谢您的帮助。我可以在admin(localhost:8000 / admin)中上载图像,更改图像...,但是问题是,在(localhost:8000)中看不到图像。
opportunity.html
{
public function jobs(){
return $this->hasMany('App\Job','employer_id');
}
}
views.py
{% extends "frontend/base.html" %} {% load static %} {% block title %}Opportunities{% endblock %} {% block content %}
<section id="blog" class="container">
<div class="blog">
<div class="row">
<div class="col-md-10">
<div class="blog-item">
<div class="row">
<div class="col-xs-12 col-sm-2">
</div>
<div class="col-xs-12 col-sm-10 blog-content">
<a href="#"><img class="img-responsive img-blog" src="{{ opportunity.image1 }}" width="100%" alt="" /></a>
<h4>{{ opportunity.heading1 }}</h4>
<p>{{ opportunity.subheading1 }}</p>
<a class="btn btn-primary readmore">{{ opportunity.link1 }} <i class="fa fa-angle-right"></i></a>
</div>
</div>
</div>
</div>
<aside class="col-md-4">
</aside>
</div>
</div>
</section>
{% endblock %}
admin.py
def opportunities(request):
navbar = get_object_or_404(Navbar, ~Q(status='draft'))
opportunity = get_object_or_404(Opportunity, ~Q(status='draft'))
context = {
"opportunity": opportunity,
"navbar": navbar,
}
return render(request, 'frontend/opportunities.html', context)
models.py
class OpportunityAdmin(admin.ModelAdmin):
list_display = ('heading1', 'author', 'published', 'status',)
list_filter = ('status', 'created', 'published', 'author')
admin.site.register(Opportunity, OpportunityAdmin)
urls.py
class Opportunity(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
image1 = models.ImageField(upload_to = 'pic_folder/')
heading1 = models.TextField(max_length=500)
subheading1=models.TextField(max_length=500)
link1 =models.CharField(max_length=30)
author = models.ForeignKey(User, related_name='opportunity')
published = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=9, choices=STATUS_CHOICES, default='draft')
def __str__(self):
return self.heading1
settings.py
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include('frontend.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
下面是localhost:8000 / admin的屏幕快照,它是管理门户 下面是localhost:8000的屏幕截图,它是html模板
答案 0 :(得分:0)
<img class="img-responsive img-blog" src="{{ opportunity.image1 }}" width="100%" alt="" />
更正上面的行,如下所示
<img class="img-responsive img-blog" src="{{ opportunity.image1.url }}" width="100%" alt="" />