How to pass a specific model field to views' functions or methods?

658 views Asked by At

I'm using Django 1.8 . I have model called Article with an article_url field. I want to pass this url in views to scrape it. How can I do it?

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})

I think it might be something like this, but it doesn't work. Actually I don't know how to pass a specific model field, not all of objects, to a view function or method.

1

There are 1 answers

0
sheshkovsky On

I could solve my problem using this piece of code in views:

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':links})

I've tried to define article variable and assign an article reading the article_id from url. Then call its field article_url using dot "." notation easily.