【发布时间】:2015-08-22 16:21:34
【问题描述】:
我正在使用 Django 1.8 。我有一个名为 Article 的模型,带有 article_url 字段。我想在视图中传递这个 url 来抓取它。我该怎么做?
models.py
class Article(models.Model):
name = models.CharField(blank=False, max_length = 250)
article_url = models.URLField()
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
def __unicode__(self):
return self.name
views.py
from django.shortcuts import render, get_object_or_404
from django.views import generic
from bs4 import BeautifulSoup
import requests
from .models import Article
class IndexView(generic.ListView):
template_name = 'index.html'
context_object_name = 'latest_article_list'
def get_queryset(self):
"""Return the last five published articles."""
return Article.objects.order_by('-pub_date')[:5]
def detail(request, article_id):
article = get_object_or_404(Article, pk=article_id)
html = Article.article_url
read = requests.get(html)
soup = BeautifulSoup(read.content)
links = soup.find_all("a")
return render(request, 'detail.html', {'article': article, 'links':link})
我认为它可能是这样的,但它不起作用。实际上我不知道如何将特定的模型字段(不是所有对象)传递给视图函数或方法。
【问题讨论】:
-
这段代码没有任何意义。 DetailView 中的类级别的请求/汤的内容是什么?你想做什么?
-
你到底想做什么?将通过这个 DetailView 渲染什么以及渲染到哪个模板?
-
您需要阅读文档并可能首先遵循 Django 教程(docs.djangoproject.com/en/1.8/intro/tutorial01 ...编写您的第一个视图在第 3 部分)。只是在 .py 文件中输入随机的代码不会让你有任何收获
-
但是你为什么要关心它是一个字段还是整个对象呢?您始终可以使用点符号访问对象上的字段。
-
那么请显示您正在执行该操作的实际代码。您显示的代码不会引发该错误,即使它有任何意义。