how to save data in the db django model?

2024/9/20 15:17:16

Good day, I can't really understand what I'm doing wrong in here. I was using this function base view to store my scrap data in the database with the django model, but now it's not saving any more. I can't really understand why. Any idea?

def weather_fetch(request):context = Nonecorrected_rainChance = Noneurl = 'http://weather.news24.com/sa/cape-town'extracted_city = url.split('/')[-1]city = extracted_city.replace('-', " ")print(city)url_request = urlopen(url)soup = BeautifulSoup(url_request.read(), 'html.parser')city_list = soup.find(id="ctl00_WeatherContentHolder_ddlCity")city_as_on_website = city_list.find(text=re.compile(city, re.I)).parentcityId = city_as_on_website['value']json_url = "http://weather.news24.com/ajaxpro/TwentyFour.Weather.Web.Ajax,App_Code.ashx"headers = {'Content-Type': 'text/plain; charset=UTF-8','Host': 'weather.news24.com','Origin': 'http://weather.news24.com','Referer': url,'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/48.0.2564.82 Chrome/48.0.2564.82 Safari/537.36','X-AjaxPro-Method': 'GetCurrentOne'}payload = {"cityId": cityId}request_post = requests.post(json_url, headers=headers, data=json.dumps(payload))data = re.sub(r"new Date\(Date\.UTC\((\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)\)\)", convert_date, request_post.text)data = data.strip(";/*")data = json.loads(data)forecast = data['Forecast']if forecast["Rainfall"] == '*':rainChance = 0corrected_rainChance = rainChanceelse:try:obj = WeatherData.objects.get_or_create(min_temp=forecast["LowTemp"], high_temp=forecast["HighTemp"],date=forecast["Date"], wind_speed=forecast["WindSpeed"], rain=corrected_rainChance)except WeatherData.DoesNotExist:obj = WeatherData.objects.get_or_create(min_temp=forecast["LowTemp"], high_temp=forecast["HighTemp"],date=forecast["Date"], wind_speed=forecast["WindSpeed"],rain=corrected_rainChance)obj.save()context = {'context': obj}print(context)return render(request, 'forecastApp/pages/fetch_weather.html', context)class WeatherData(models.Model):date = models.DateTimeField(default=timezone.now)wind_speed = models.DecimalField(max_digits=3, decimal_places=1)high_temp = models.DecimalField(max_digits=3, decimal_places=1)min_temp = models.DecimalField(max_digits=3, decimal_places=1)rain = models.IntegerField(default=0)def __str__(self):return ' '.join(str([self.date.month, self.date.day, self.date.year]))
Answer

There is definitely a problem with your try/except block. Amusing your code works until the object creation, you should change that part to:

if forecast["Rainfall"] == '*':rainChance = 0corrected_rainChance = rainChance
else:obj = WeatherData.objects.get_or_create(min_temp=forecast["LowTemp"], high_temp=forecast["HighTemp"],date=forecast["Date"], wind_speed=forecast["WindSpeed"], rain=corrected_rainChance)# obj.save()  --> you don't need to save the obj again.context = {'context': obj}print(context)
https://en.xdnf.cn/q/119477.html

Related Q&A

Move existing jointplot legend

I tried answers from a previous question to no avail in Matplotlib 1.5.1. I have a seaborn figure:import seaborn as sns %matplotlib inline import matplotlib.pyplot as plt import numpy as np tips = sns.…

timezone conversion of a large list of timestamps from an excel file with python

I have an excel file named "hello.xlsx". There is a column of timestamps that has a lot of rows (more than 80,000 rows for now). The file basically looks like this:03/29/2018 19:24:5003/29/20…

N_gram frequency python NTLK

I want to write a function that returns the frequency of each element in the n-gram of a given text. Help please. I did this code fo counting frequency of 2-gramcode:from nltk import FreqDistfrom nltk.…

Is there a way to have a list of 4 billion numbers in Python?

I made a binary search function and Im curious what would happen if I used it on 4 billion numbers, but I get a MemoryError every time I use it. Is there a way to store the list without this issue?

ValueError: invalid literal for int() with base 10: when it worked before

Im having some issues with my program, basically what Im trying to do is Stenography, insert an image into another image and then extract the secret image.My program is able to insert just fine, but ex…

How to fetch the current branch from Jenkins?

I would like to query Jenkins using its API and Python to fetch the branch that is currently ready to be built.How can I do that?

How to vertically stretch graphs with matplotlib subplot [duplicate]

This question already has answers here:How do I change the size of figures drawn with Matplotlib?(16 answers)Closed 5 years ago.With the following code, I try to plot 12 different histograms in one pi…

Python Selenium Traceback (most recent call last):

Im trying to use selenium for a python web scraper but when I try to run the program I get the following error: "/Applications/Python 3.8/IDLE.app/Contents/MacOS/Python" "/Applications/P…

getting error while installing opencv via pip

python version = Python 3.8.0pip version = 19.3.1C:\Users\Sami Ullah Ch>pip3 install opencv-pythonERROR: Could not find a version that satisfies the requirement opencv-python (from versions: none)

Check whether text contains x numbers in a row [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 8 years ago.Improve…