'Model form create within listview in Django using CBV

Hi i m learning django by creating weather app. I dont know this is the correct way of doing this.I need a form within listview for adding city to user and I'm using CBV .but form is not present in website.what can I do?

views.py

from urllib import request
from django.shortcuts import render

import requests
from datetime import datetime
from .models import City
from pytz import timezone
from django.views.generic import ListView

from .forms import CityForm
from django.views.generic.edit import FormMixin, FormView


class Cities(FormMixin,ListView):
    model=City
    template_name='home.html'
    form_class=CityForm
    success_url='/'


    def get_context_data(self, *, object_list=None, **kwargs):
        context =super(Cities, self).get_context_data(**kwargs)
        
        weather_data=[]

        for city in City.objects.all():
            url=f'https://api.openweathermap.org/data/2.5/weather?q={city}'
            data=requests.get(url).json()
 
            if data["cod"] != "404":

                now_asia =datetime.fromtimestamp(data['timezone']).strftime('%a,%b %d %Y')
                payload={   'city':data['name'],
                    'weather':data['weather'][0]['main'],
                    'icon':data['weather'][0]['icon'],
                    'fahrenheit':data['main']['temp'],
                    'celsius':int(data['main']['temp']-273),
                    'pressure':data['main']['pressure'],
                    'humidity':data['main']['humidity'],
                    'description':data['weather'][0]['description'],
                    'date' :now_asia,

                    }

                weather_data.append(payload)
            else:
                weather_data={'invalid_city':f'{city} City not found.\n Enter valid city'}
        print(context)
        context={'weather_data':weather_data}
        return context

forms.py

from django.forms import ModelForm
from .models import City


class CityForm(ModelForm):
    class Meta:
        model=City
        fields=['name']

home.html

    {% csrf_token %}
    {{form}}
    <button class="btn" type="submit" >Add city</button>

enter image description here



Solution 1:[1]

In get_context_data change at the end

   context['weather_data'] = weather_data
   return context

You just want to add another key but not overwrite the whole context

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Razenstein