media.py发生错误,看起来我的网址是无。但我不明白为什么。如何将url等于用户发布的url?如果你看到我的views.py,我试着像那样设置它。 url等于self.request.GET.get('url')。我做错了吗?
media.py 导入json import urllib2 来自urllib2导入请求 来自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)
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')
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)
答案 0 :(得分:1)
在views.py中,请执行以下操作:
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]))