我有这段代码从用户发布的网址中提取图片。我没有收到任何错误,但我不确定如何将提取的图像显示到我的index.html。 在这里;是我的views.py
class PostCreateView(CreateView):
model = Post
form_class = PostForm
template_name = 'main/add_post.html'
def form_valid(self, form):
self.object = form.save(commit=False)
# any manual settings go here
self.object.moderator = self.request.user
url = self.request.GET.get('url', False)
if url:
image = extract(url)
self.object.save()
return HttpResponseRedirect(reverse('post', args=[self.object.slug]))
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostCreateView, self).dispatch(request, *args, **kwargs)
这里我有image = extract(url) extract方法来自media.py。 因为我没有得到任何错误,我假设至少语法是正确的。 现在我想将该图像显示到我的index.html。 我认为post.image会完成这项工作,但没有任何显示。
在这里;是我的media.py
import json
import urllib2
from urllib2 import Request
from goose import Goose
def get_content(url):
"""This function is intended to return content from url.
:param url: URL to get content
:return: The response from url
"""
req = urllib2.Request(url, headers={'User-Agent': "Magic Browser"})
response = urllib2.Request.urlopen(req).read()
return response
def extract(url):
url = get_content(url)
g = Goose()
article = g.extract(url=url)
resposne = {'image':article.top_image.src}
return json.dumps(resposne)
my models.py以防万一
class Post(models.Model):
category = models.ForeignKey(Category)
pub_date = models.DateTimeField(auto_now_add = True)
title = models.CharField(max_length = 100)
content = FroalaField()
url = models.URLField(max_length=250, blank=True, null=True)
moderator = models.ForeignKey(User)
rank_score = models.FloatField(default= 1)
views = models.IntegerField(default=0)
image = models.ImageField(upload_to="images",blank=True, null=True)
slug = models.CharField(max_length=100, unique=True)
objects = models.Manager()
答案 0 :(得分:0)
您已从请求数据中提取了网址并检索了图片,但您根本没有做任何事情。我猜你需要把它保存在Post对象的某个地方。