如何修复从视图传递到html的变量

时间:2019-05-29 11:25:12

标签: python django

我在将变量“ res”从视图传递到index.html时遇到问题,它会返回html页面中的最后一个结果

查看文件:

def index(request):

    posts = Layout.objects.all()
    urlpost = SiteUrls.objects.all()[:20]


    field_value = SiteUrls.objects.values_list('site_url', flat=True)

    for site_url in field_value:
        print(site_url)
        res = os.system("ping -n 1 " + site_url )

        if res == 0:
            res = "connected"
        else:
            res = "not connected"

    context = {
        'posts':posts,
        'urlpost':urlpost,
        'res': res
    }

    return render (request, 'posts/index.html', context)

html文件:

      <table>
        <tbody>
            {% for SiteUrls in urlpost %}
          <tr>
            <td>{{SiteUrls.site_title}}</td>
            <td>{{SiteUrls.site_url}}</td>

            <td> {{res}} </td>

            <td><a style="margin-bottom:10px" class="waves-effect waves-light btn">open Site</a></td>
          </tr>
            {% endfor %}
        </tbody>
      </table>

我想获取每一行的具体结果

3 个答案:

答案 0 :(得分:1)

请勿使用import requests from bs4 import BeautifulSoup as bs from selenium import webdriver url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) num_pages = int(soup.select_one('.page-number').text.split('/')[1]) for page in range(2, num_pages + 1): r = s.get(url.format(page)) soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) all_links = [item for i in all_links for item in i] d = webdriver.Chrome() for article in all_links: d.get(article) soup = bs(d.page_source, 'lxml') [t.extract() for t in soup(['style', 'script', '[document]', 'head', 'title'])] visible_text = soup.getText() try: print(soup.select_one('.post-title').text) except: print(article) print(soup.select_one('h1').text) break d = webdriver.Chrome() for article_links in all_links: d.get(article) soup = bs(d.page_source, 'lxml') # nie moj !!!!!! # 2.2. Post contents contents = [] for all_links in article_links: soup = bs((article), 'html.parser') content = soup.find('section', attrs={'class': 'post-content'}) contents.append(content) # 2.1. Authors authors = [] for all_links in article: soup = bs(article, 'html.parser') author = soup.find('span', attrs={'class': 'author-content'}) authors.append(author) # POSTGRESQL CONNECTION # 1. Connect to local database using psycopg2 import psycopg2 hostname = 'balarama.db.elephantsql.com' username = 'yagoiucf' password = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx' database = 'yagoiucf' conn = psycopg2.connect(host='balarama.db.elephantsql.com', user='yagoiucf', password='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', dbname='yagoiucf') conn.close() 。而是使用这些对象,并将您的值添加为附加属性。

请注意,在您的代码中,您将 database.execSQL("CREATE TABLE IF NOT EXISTS " + TableName + " ( rowid INTEGER PRIMARY KEY AUTOINCREMENT, Raqam VARCHAR, ChandBor INT(3));"); 查询限制为20个对象,但随后对数据库中的所有Cursor cursorLcl = database.rawQuery("SELECT *," + TableName + ".rowid AS rowid" + " FROM " + TableName, null); 进行了ping操作。我假设您只想ping通这20 .values_list()

SiteUrls

模板:

SiteUrls

此外,通常像在此处一样在Web请求中调用系统进程也被认为是一个坏主意。一旦使它起作用,我鼓励您研究任务队列的概念。

答案 1 :(得分:0)

如果urlpostres中的对象顺序相同,则可以使用python的zip函数并将它们合并为元组,然后在模板中遍历此元组列表

答案 2 :(得分:0)

也许您可以将其作为临时属性传递

def index(request):

    posts = Layout.objects.all()
    urlpost = SiteUrls.objects.all()[:20]
    field_value = SiteUrls.objects.values_list('site_url', flat=True)

    for site_url in field_value:
        print(site_url)
        res = os.system("ping -n 1 " + site_url )

        if res == 0:
            site_url.res = "connected"
        else:
            site_url.res = "not connected"

        context = {
            'posts':posts,
            'urlpost':urlpost,
            }

    return render (request, 'posts/index.html', context)

,您可以像这样在模板中循环访问

{{SiteUrls.res}}