0

So, I'm basically trying to make a website that brings information about cities when you input a city name. Right now all I'm able to, successfully, display is the weather report of a city. I'm trying to bring some news headlines as well.

I tried this code. And this, as far as I know about the language, should have worked.

views.py

from django.shortcuts import render
import requests
import json
from datetime import datetime

def index(request):
    try:
        if request.method == 'POST':
            API_KEY = '#################################'
            city_name = request.POST.get('city')
            url = f'https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={API_KEY}&units=metric'   
            response = requests.get(url).json()
            current_time = datetime.now()
directives, it will take this format Day, Month Date Year, Current Time 
            formatted_time = current_time.strftime("%A, %B %d %Y, %H:%M:%S %p")
information in one dictionary
            city_weather_update = {
                'city': city_name,
                'description': response['weather'][0]['description'],
                'icon': response['weather'][0]['icon'],
                'temperature': 'Temperature: ' + str(response['main']['temp']) + ' °C',
                'country_code': response['sys']['country'],
                'wind': 'Wind: ' + str(response['wind']['speed']) + 'km/h',
                'humidity': 'Humidity: ' + str(response['main']['humidity']) + '%',
                'time': formatted_time
            }

        else:
            city_weather_update = {}
        context = {'city_weather_update': city_weather_update}
        return render(request, 'index.html', context)
 
    except:
        return render(request, 'error.html')

def news(request):
    try:
        if request.method == 'POST':
            API_KEY = '#################################'
            city = request.POST.get('city')
            
            url = f'https://newsapi.org/v2/top-headlines?q={city}&apiKey={API_KEY}'
            response = requests.get(url)
            data = response.json()

            articles = data['articles']
        else:
            articles = {}

        context = {'articles': articles}    
        return render(request, 'index.html', context)

    except:
        return render(request, 'error.html')

index.html

{% extends 'base.html' %}
{% block content %}
<div class="row justify-content-center my-5">
    <div class="col-md-5">
        <div class="mt-4 p-5 bg-success text-white rounded mb-3">
            <h1>Weather Update App</h1>
        </div>
        <form action="" method="POST">
          {% csrf_token %}
          <div class="input-group">
            <input type="text" required class="form-control" name="city" placeholder="Search City.......">
            <div class="input-group-append">
              <button class="btn btn-success" type="submit">
                Search
              </button>
            </div>
          </div>
        </form>
        <hr>
        <div class="card">
            <div class="card-body">
                <img src="http://openweathermap.org/img/w/{{ city_weather_update.icon }}.png" alt="">
                <div class="card-text float-end">{{ city_weather_update.time }}</div>
                <div class="card-text"><h5>{{ city_weather_update.city }} {{ city_weather_update.country_code }}</h5></div>
                <div class="card-text"><h6>{{ city_weather_update.temperature }}</h6></div>
                <div class="card-text"><h6>{{ city_weather_update.description | title }}</h6></div>
                <div class="card-text"><h6>{{ city_weather_update.wind }}</h6></div>
                <div class="card-text"><h6>{{ city_weather_update.humidity }}</h6></div>
            </div>
        </div>
        {% if articles %}
            <h2>News Articles:</h2>
            {% for article in articles %}
                <div class="card my-3">
                    <div class="card-body">
                        <h5 class="card-title">{{ article.title }}</h5>
                        <p class="card-text">{{ article.description }}</p>
                        <a href="{{ article.url }}" class="btn btn-primary">Read More</a>
                    </div>
                </div>
            {% endfor %}
        {% else %}
            <p>No news articles found for the specified city.</p>
        {% endif %}
    </div>
</div>

{% endblock %}

For the weather I'm using the openweather API and for the news I'm trying to get newsapi.org's API to work.

Any help is appreciated :D

1 Answers1

0

Do you ever tell Django to render the news view? You didn't include your urls, but I assume your 'hooked-up' view is index, considering it is the one that you can sucessfully display.

You have two different views with two separate contexts: context = {'city_weather_update': city_weather_update} and context = {'articles': articles}.

You could try to have the news take 'city_name' as an argument and return 'articles' (and not render anything), and then instead call news from index. That way, you can pass all of the context through one view.

This would make your index context:

context = {'city_weather_update': city_weather_update, 'articles': news(city_name)}

Please let me know if I am misunderstanding your code or what you are trying to do.

luisa
  • 1
  • 2