I build a social media application where all actions are concluded in the same count. However with the like button i get an error even if the code looks exactly the same as the dislike version. The error is:
IntegrityError at /like-post
null value in column "num_interactions_total" of relation "core_likepost" violates not-null constraint
DETAIL: Failing row contains (98, a4aaa95b-a3a5-49a6-8f63-de768bfa0786, 2023-02-02 18:01:13.121023+00, , 1, null, 7).
but the num_interactions_total count is already deleted and does not exist in the model or views.py anymore. I've also deleted the migrations. I'm using the postgresql database.
I´m a little confused, why it gives me an error only with this button and not with all the others... How do I avoid the null error?
Here are the models and views from like and dislike:
def like_pdf(instance, filename):
ext = filename.split('.')[-1]
filename = 'post{}.{}'.format(instance.interactions_total, ext)
return os.path.join('uploads', filename)
class LikePost(models.Model):
post_id = models.CharField(max_length=500)
created_at = models.DateTimeField(default=datetime.now)
num_likes_total = models.IntegerField(default=0)
interactions_total = models.IntegerField(default=0)
pdf_like = models.FileField(upload_to=like_pdf, default=None, null=True)
def __str__(self):
return self.post_id
def dislike_pdf(instance, filename):
ext = filename.split('.')[-1]
filename = 'post{}.{}'.format(instance.interactions_total, ext)
return os.path.join('uploads', filename)
class DislikePost(models.Model):
post_id = models.CharField(max_length=500)
created_at = models.DateTimeField(default=datetime.now)
num_dislikes_total = models.IntegerField(default=0)
interactions_total = models.IntegerField(default=0)
pdf_dislike = models.FileField(upload_to=dislike_pdf, default=None, null=True)
def __str__(self):
return self.post_id
def like_post(request):
post_id = request.GET.get('post_id')
post = Post.objects.get(id=post_id)
post.number_of_likes = post.number_of_likes + 1
num_likes_total = LikePost.objects.count() + 1
interactions_total = InteractionPost.objects.count()
new_like = LikePost.objects.create(post_id=post_id, num_likes_total=num_likes_total, interactions_total=interactions_total)
new_like.save()
new_interaction = InteractionPost.objects.create(post_id=post_id)
new_interaction.save()
post.interaction_count = post.interaction_count + 1
likes_string = ""
word = "like "
i = 0
while i < 1:
post.likes_string = post.likes_string + word + os.linesep
i += 1
post.save()
# create pdf dislike
buffer = io.BytesIO()
countobject = UserCount.objects.first()
p = canvas.Canvas(buffer, pagesize=A4)
x_start = 50
y_start = 200
x = 100
y = 275
p.roundRect(x_start, y_start, 500, 400, 10, stroke=1, fill=0)
p.roundRect(x, y, 400, 300, 10, stroke=1, fill=0)
p.drawString(100, 700, "new_interaction: like_post // user no.:")
p.drawString(100, 675, str(new_like.created_at))
p.drawString(200, 650, str(post.num_post))
p.drawString(100, 650, "post no.:")
p.drawString(400, 700, str(countobject))
p1 = Paragraph(post.dislikes_string)
p1.wrapOn(p, 400, 1000)
p1.drawOn(p, 200, 700)
p2 = Paragraph(post.likes_string)
p2.wrapOn(p, 400, 1000)
p2.drawOn(p, 0, 800)
p.save()
buffer.seek(0)
new_like.pdf_like.save(f"post{interactions_total}.pdf", buffer)
new_like.save()
return redirect('/')
def dislike_post(request):
post_id = request.GET.get('post_id')
post = Post.objects.get(id=post_id)
post.number_of_dislikes = post.number_of_dislikes + 1
num_dislikes_total = DislikePost.objects.count() + 1
interactions_total = InteractionPost.objects.count()
new_dislike = DislikePost.objects.create(post_id=post_id, num_dislikes_total=num_dislikes_total, interactions_total=interactions_total)
new_dislike.save()
new_interaction = InteractionPost.objects.create(post_id=post_id)
new_interaction.save()
post.interaction_count = post.interaction_count + 1
dislikes_string = ""
word = "dislike "
i = 0
while i < 1:
post.dislikes_string = post.dislikes_string + word + os.linesep
i += 1
post.save()
#create pdf dislike
buffer = io.BytesIO()
countobject = UserCount.objects.first()
p = canvas.Canvas(buffer, pagesize=A4, )
x_start = 50
y_start = 200
x = 100
y = 275
p.roundRect(x_start, y_start, 500, 400, 10, stroke=1, fill=0)
p.roundRect(x, y, 400, 300, 10, stroke=1, fill=0)
p.drawString(100, 700, "new_interaction: dislike_post // user no.:")
p.drawString(100, 675, str(new_dislike.created_at))
p.drawString(200, 650, str(post.num_post))
p.drawString(100, 650, "post no.:")
p.drawString(400, 700, str(countobject))
p1 = Paragraph(post.dislikes_string)
p1.wrapOn(p, 400, 1000)
p1.drawOn(p, 0, 300)
p2 = Paragraph(post.likes_string)
p2.wrapOn(p, 400, 1000)
p2.drawOn(p, 110, 600)
p.save()
buffer.seek(0)
new_dislike.pdf_dislike.save(f"post{interactions_total}.pdf", buffer)
new_dislike.save()
return redirect('/')
I know the code is quite messy.But where does the error come from?
Problem is you deleted in models.py, migration but forgot delete in database.
You can manually delete it in db, or do it with commands console
Assum you have 2 migrations in app test_app:
0001_test_1.py
0002_test_2.py #have column num_interactions_total
Now want delete num_interactions_total. You can revert migrations like:
python manage.py migrate test_app 0001_test_1
It will back your database to migration 0001_test_1, revert all changed in 0002_test_2 - delete column num_interactions_total
Related
enter image description hereI made my autobot for coin trade.
I'm using iterm2 terminal to operate my code.
But there's some problem I don't understand.
first I use the same fuction by changing parameter, symbolname etc.
but on the terminal window for A coin, there's only 'timestamp' message.
i can't tell if it is error or not because there's no error message
and i didn't code print('timestamp')
on the other terminal windows for other coin, there's no such a message.
I guess my explanation is not enough.
but if you have any idea about this kind of situations, please tell me.
I'm using python.
thank you already!!
sometimes, although i didn't change anytihng.
'timestamp' message was disappeared.
enter image description here
enter code here
def runBot(symbol, second=int):
try:
subtitle = 'B'
fourth_interval = '30m'
symbol = symbol
path = path
df_1 = callChart(exchange=exchange, symbol=symbol, interval='15m')
df_2 = callChart(exchange=exchange, symbol=symbol, interval='5m')
df_3 = callChart(exchange=exchange, symbol=symbol, interval='1m')
df_4 = callChart(exchange=exchange, symbol=symbol, interval='30m')
df_5 = callChart(exchange=exchange, symbol=symbol, interval='1h')
df_6 = callChart(exchange=exchange, symbol=symbol, interval='4h')
df_7 = callChart(exchange=exchange, symbol=symbol, interval='2h')
n4hma2 = df_6.ma20[-1]
n4hma6 = df_6.ma60[-1]
n4hma8 = df_6.ma80[-1]
p4h_rsi = df_6.rsi[-2]
p4h_open = df_6.open[-2]
p4h_close = df_6.close[-2]
n1hma2 = df_5.ma20[-1]
n1hma6 = df_5.ma60[-1]
n1hma8 = df_5.ma80[-1]
n1h_low = df_5.low[-1]
n1h_high = df_5.high[-1]
n1h_open = df_5.open[-1]
p1h_rsi = df_5.rsi[-2]
p1hma2 = df_5.ma20[-2]
p1hma6 = df_5.ma60[-2]
p1hma8 = df_5.ma80[-2]
p1h_close = df_5.close[-2]
n30ma2 = df_4.ma20[-1]
n30ma6 = df_4.ma60[-1]
n30ma8 = df_4.ma80[-1]
n30_high = df_4.high[-1]
n30_low = df_4.low[-1]
n30_open = df_4.open[-1]
p30_rsi = df_4.rsi[-2]
p30_rsi = df_4.rsi[-2]
p30_close = df_4.close[-2]
pp30_close = df_4.close[-3]
ppp30_close = df_4.close[-4]
p30ma2 = df_4.ma20[-2]
p30ma6 = df_4.ma60[-2]
p30ma8 = df_4.ma80[-2]
pp30ma2 = df_4.ma20[-4]
pp30ma6 = df_4.ma60[-4]
pp30ma8 = df_4.ma80[-4]
ppp30ma2 = df_4.ma20[-4]
ppp30ma6 = df_4.ma60[-4]
ppp30ma8 = df_4.ma80[-4]
p4_30ma2 = df_4.ma20[-5]
p4_30ma6 = df_4.ma60[-5]
p4_30ma8 = df_4.ma80[-5]
n_price = df_1.close[-1]
n15ma2 = df_1.ma20[-1]
n15ma6 = df_1.ma60[-1]
n15ma8 = df_1.ma80[-1]
p15_close = df_1.close[-2]
p15_open = df_1.open[-2]
n15_high = df_1.high[-1]
n15_low = df_1.low[-1]
p15ma2 = df_1.ma20[-2]
p15ma6 = df_1.ma60[-2]
p15ma8 = df_1.ma80[-2]
n5ma2 = df_2.ma20[-1]
n5ma6 = df_2.ma60[-1]
n5ma8 = df_2.ma80[-1]
n5_high = df_2.high[-1]
n5_low = df_2.low[-1]
p5ma2 = df_2.ma20[-2]
p5ma6 = df_2.ma60[-2]
p5ma8 = df_2.ma80[-2]
p5_close = df_2.close[-2]
n1ma2 = df_3.ma20[-1]
n1ma6 = df_3.ma60[-1]
n1ma8 = df_3.ma80[-1]
p1m_close = df_3.close[-2]
p1ma2 = df_3.ma20[-2]
p1ma6 = df_3.ma60[-2]
p1ma8 = df_3.ma80[-2]
n2hma2 = df_7.ma20[-1]
n2hma6 = df_7.ma60[-1]
n2hma8 = df_7.ma80[-1]
now = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
now_date = datetime.date(now.year, now.month, now.day)
now_time = datetime.time(now.hour, now.minute, now.second)
what_day = now.weekday()
timestamp = time.mktime(datetime.datetime.strptime(str(f'{now_date} {now_time}'), '%Y-%m-%d %H:%M:%S').timetuple())
mt4 = datetime.datetime.utcnow() + datetime.timedelta(hours=3)
mt4_date = datetime.date(mt4.year, mt4.month, mt4.day)
mt4_time = datetime.time(mt4.hour, mt4.minute, mt4.second)
total_balance = exchange.fetch_balance()['USDT']['total']
total_balance2 = exchange2.fetch_balance()['USDT']['total']
total_balance5 = exchange5.fetch_balance()['USDT']['total']
print(colors.fg.blue, f'{subtitle}', colors.reset, colors.fg.green, f'{symbol}', colors.reset, f'{n_price}', colors.fg.yellow, f'{now_date} {now_time}', colors.reset)
I'm getting the following error
ValueError: feature_names mismatch: ['Have_IP', 'Have_At', 'URL_Length', 'URL_Depth', 'Redirection', 'https_Domain', 'TinyURL', 'Prefix/Suffix', 'DNS_Record', 'Web_Traffic', 'Domain_Age', 'Domain_End', 'iFrame', 'Mouse_Over', 'Right_Click', 'Web_Forwards'] ['0']
expected https_Domain, DNS_Record, Domain_Age, URL_Depth, Have_At, iFrame, Have_IP, TinyURL, Redirection, Web_Traffic, Web_Forwards, Mouse_Over, Prefix/Suffix, Right_Click, URL_Length, Domain_End in input data
training data did not have the following fields: 0
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(320, 260, 191, 51))
font = QtGui.QFont()
font.setPointSize(16)
self.label_2.setFont(font)
self.label_2.setStyleSheet("color: rgb(255, 0, 0);")
self.label_2.setObjectName("label_2")
self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(250, 140, 281, 31))
self.textEdit.setObjectName("textEdit")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(360, 210, 80, 25))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.UrlfeatureExtraction)
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(120, 150, 91, 16))
self.label_3.setObjectName("label_3")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 30))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", " PHISHING WEBSITE DETECTION"))
self.pushButton.setText(_translate("MainWindow", "DETECT"))
self.label_2.setText(_translate("MainWindow", "ANSWER IS:-"))
self.label_3.setText(_translate("MainWindow", "ENTER URL"))
# 1.Domain of the URL (Domain)
def getDomain(self,url):
domain = urlparse(url).netloc
if re.match(r"^www.", domain):
domain = domain.replace("www.", "")
return domain
# 2.Checks for IP address in URL (Have_IP)
def havingIP(self,url):
try:
ipaddress.ip_address(url)
ip = 1
except:
ip = 0
return ip
# 3.Checks the presence of # in URL (Have_At)
def haveAtSign(self,url):
if "#" in url:
at = 1
else:
at = 0
return at
# 4.Finding the length of URL and categorizing (URL_Length)
def getLength(self,url):
if len(url) < 54:
length = 0
else:
length = 1
return length
# 5.Gives number of '/' in URL (URL_Depth)
def getDepth(self,url):
s = urlparse(url).path.split('/')
depth = 0
for j in range(len(s)):
if len(s[j]) != 0:
depth = depth + 1
return depth
# 6.Checking for redirection '//' in the url (Redirection)
def redirection(self,url):
pos = url.rfind('//')
if pos > 6:
if pos > 7:
return 1
else:
return 0
else:
return 0
# 7.Existence of “HTTPS” Token in the Domain Part of the URL (https_Domain)
def httpDomain(self,url):
domain = urlparse(url).netloc
if 'https' in domain:
return 1
else:
return 0
# listing shortening services
shortening_services = r"bit\.ly|goo\.gl|shorte\.st|go2l\.ink|x\.co|ow\.ly|t\.co|tinyurl|tr\.im|is\.gd|cli\.gs|" \
r"yfrog\.com|migre\.me|ff\.im|tiny\.cc|url4\.eu|twit\.ac|su\.pr|twurl\.nl|snipurl\.com|" \
r"short\.to|BudURL\.com|ping\.fm|post\.ly|Just\.as|bkite\.com|snipr\.com|fic\.kr|loopt\.us|" \
r"doiop\.com|short\.ie|kl\.am|wp\.me|rubyurl\.com|om\.ly|to\.ly|bit\.do|t\.co|lnkd\.in|db\.tt|" \
r"qr\.ae|adf\.ly|goo\.gl|bitly\.com|cur\.lv|tinyurl\.com|ow\.ly|bit\.ly|ity\.im|q\.gs|is\.gd|" \
r"po\.st|bc\.vc|twitthis\.com|u\.to|j\.mp|buzurl\.com|cutt\.us|u\.bb|yourls\.org|x\.co|" \
r"prettylinkpro\.com|scrnch\.me|filoops\.info|vzturl\.com|qr\.net|1url\.com|tweez\.me|v\.gd|" \
r"tr\.im|link\.zip\.net"
# 8. Checking for Shortening Services in URL (Tiny_URL)
def tinyURL(self,url):
match = re.search(self.shortening_services, url)
if match:
return 1
else:
return 0
# 9.Checking for Prefix or Suffix Separated by (-) in the Domain (Prefix/Suffix)
def prefixSuffix(self,url):
if '-' in urlparse(url).netloc:
return 1 # phishing
else:
return 0 # legitimate
def get_ipython(self):
pass
self.get_ipython().system('pip install python-whois')
# 12.Web traffic (Web_Traffic)
def web_traffic(self,url):
try:
# Filling the whitespaces in the URL if any
url = urllib.parse.quote(url)
rank = \
BeautifulSoup(urllib.request.urlopen("http://data.alexa.com/data?cli=10&dat=s&url=" + url).read(),
"xml").find(
"REACH")['RANK']
rank = int(rank)
except TypeError:
return 1
if rank < 100000:
return 1
else:
return 0
# 13.Survival time of domain: The difference between termination time and creation time (Domain_Age)
def domainAge(self,domain_name):
creation_date = domain_name.creation_date
expiration_date = domain_name.expiration_date
if (isinstance(creation_date, str) or isinstance(expiration_date, str)):
try:
creation_date = datetime.strptime(creation_date, '%Y-%m-%d')
expiration_date = datetime.strptime(expiration_date, "%Y-%m-%d")
except:
return 1
if ((expiration_date is None) or (creation_date is None)):
return 1
elif ((type(expiration_date) is list) or (type(creation_date) is list)):
return 1
else:
ageofdomain = abs((expiration_date - creation_date).days)
if ((ageofdomain / 30) < 6):
age = 1
else:
age = 0
return age
# 14.End time of domain: The difference between termination time and current time (Domain_End)
def domainEnd(self,domain_name):
expiration_date = domain_name.expiration_date
if isinstance(expiration_date, str):
try:
expiration_date = datetime.strptime(expiration_date, "%Y-%m-%d")
except:
return 1
if (expiration_date is None):
return 1
elif (type(expiration_date) is list):
return 1
else:
today = datetime.now()
end = abs((expiration_date - today).days)
if ((end / 30) < 6):
end = 0
else:
end = 1
return end
# 15. IFrame Redirection (iFrame)
def iframe(self,response):
if response == "":
return 1
else:
if re.findall(r"[<iframe>|<frameBorder>]", response.text):
return 0
else:
return 1
# 16.Checks the effect of mouse over on status bar (Mouse_Over)
def mouseOver(self,response):
if response == "":
return 1
else:
if re.findall("<script>.+onmouseover.+</script>", response.text):
return 1
else:
return 0
# 17.Checks the status of the right click attribute (Right_Click)
def rightClick(self,response):
if response == "":
return 1
else:
if re.findall(r"event.button ?== ?2", response.text):
return 0
else:
return 1
# 18.Checks the number of forwardings (Web_Forwards)
def forwarding(self,response):
if response == "":
return 1
else:
if len(response.history) <= 2:
return 0
else:
return 1
# Function to extract features
# There are 17 features extracted from the dataset
def featureExtractions(self,url):
self.getDomain(url)
features=[]
features = [self.havingIP(url), self.haveAtSign(url),self.getLength(url),self.getDepth(url),self.redirection(url),
self.httpDomain(url),self.tinyURL(url),self.prefixSuffix(url)]
# Address bar based features (9)
# Domain based features (4)
dns = 0
try:
domain_name = whois.whois(urlparse(url).netloc)
except:
dns = 1
features.append(dns)
features.append(self.web_traffic(url))
features.append(1 if dns == 1 else self.domainAge(domain_name))
features.append(1 if dns == 1 else self.domainEnd(domain_name))
# HTML & Javascript based features (4)
try:
response = requests.get(url)
except:
response = ""
features.append(self.iframe(response))
features.append(self.mouseOver(response))
features.append(self.rightClick(response))
features.append(self.forwarding(response))
# label=0
# features.append(label)
book = xlsxwriter.Workbook('Extracted_data.xlsx')
sheet1 = book.add_worksheet()
feature_names = ['Have_IP', 'Have_At', 'URL_Length', 'URL_Depth','Redirection',
'https_Domain', 'TinyURL','Prefix/Suffix', 'DNS_Record','Web_Traffic', 'Domain_Age', 'Domain_End',
'iFrame', 'Mouse_Over','Right_Click', 'Web_Forwards']
row = 0
column = 0
for item in feature_names :
# write operation perform
sheet1.write(row, column, item)
# incrementing the value of row by one with each iterations.
column += 1
row = 1
column = 0
for item in features :
# write operation perform
sheet1.write(row, column, item)
# incrementing the value of row by one with each iterations.
column += 1
book.close()
return features
def UrlfeatureExtraction(self):
url = self.textEdit.toPlainText()
data=[]
label=0
data=self.featureExtractions(url)
# data.pop()
XGmodel = pickle.load(open('XGBoostClassifier.pkl', 'rb'))
cols_when_model_builds = XGmodel.get_booster().feature_names
print(data)
dfa=pd.DataFrame(data)
y_pred = XGmodel.predict(dfa)
predictions = [round(value) for value in y_pred]
# evaluate predictions
if predictions == 0:
value = "Legitimate"
self.label.setText(value)
else:
value = "Phishing"
self.label.setText(value);
if name == "main":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
My Xtrain and Xtest consist of 16 features and i have passed it in for the input data of the model. I even matched its sequence and no of features.
I'm not able to understand what is this error...
Please help me with this
You have 16 feature_names and 17 features.
On my page I ask for various things to the user in the form as it's a calculator that does various things, now you see, the thing is if the user does not have the value for bf I want to give the option to calculate with different values, that is why I required is False, so first what I want to archive is that if the form is empty I want to be passed as a 0 or False, how can I archive this?
I have the following form:
class CMForm(forms.Form):
age = forms.DecimalField(max_digits=2, decimal_places=0, min_value=15, max_value=80)
sex = forms.ChoiceField(choices=sex)
pregnant = forms.BooleanField(initial=False, required=False)
lactating = forms.BooleanField(initial=False, required=False)
weight = forms.DecimalField(max_digits=4, decimal_places=1, max_value=635)
height = forms.DecimalField(max_digits=4, decimal_places=1, max_value=272)
bf = forms.DecimalField(label='Body Fat(not required)', help_text='%', required=False, decimal_places=1, min_value=1, max_value=80)
activeness = forms.ChoiceField(choices=activity_level)
units = forms.ChoiceField(choices=units)
this view:
def cmr(request):
a = float(request.GET['age'])
bf = float(request.GET.get('bf', 0))
s = str(request.GET['sex'])
g = 0
if s == 'female':
g = 1
w = float(request.GET['weight'])
h = float(request.GET['height'])
act = str(request.GET['activeness'])
u = str(request.GET['units'])
p = str(request.GET.get('pregnant', 0))
lac = str(request.GET.get('lactating', 0))
dci = 0
bmrm = 10*w+6.25*h-5*a+5
bmrf = 10*w+6.25*h-5*a-161
bmi = round(w/(h/100)**2, 1)
if bf is False:
bf = round(-44.988 + (0.503 * a) + (10.689 * g) + (3.172 * bmi) - (0.026 * bmi**2) + (0.181 * bmi * g) - (0.02 * bmi * a) - (0.005 * bmi**2 * g) + (0.00021 * bmi**2 * a), 1)
tbf = w*(bf/100)
ffm = w*(1-(bf/100))
ffmi = ffm/(h/100)**2
nffmi = ffmi+6.1*(1.8-(h/100))
if p == 'on':
dci = 300
if lac == 'on':
dci = dci+500
if s == 'male':
bmr = dci+bmrm
dcis = bmrm*1.2
dcil = bmrm*1.375
dcim = bmrm*1.55
dciv = bmrm*1.725
dcie = bmrm*1.9
else:
bmr = dci+bmrf
dcis = dci+bmrf*1.2
dcil = dci+bmrf*1.375
dcim = dci+bmrf*1.55
dciv = dci+bmrf*1.725
dcie = dci+bmrf*1.9
context = {'dci': round(int(dci)),
'p': p,
'lac': lac,
'bmr': int(bmr),
'dcis': int(dcis),
'dcil': int(dcil),
'dcim': int(dcim),
'dciv': int(dciv),
'dcie': int(dcie),
'act': act,
'bmi': bmi,
'bf': bf,
'tbf': round(tbf, 1),
'ffm': round(ffm, 1),
'ffmi': round(ffmi, 1),
'nffmi': round(nffmi, 1),
}
return render(request, "calorie_maintenance_result.html", context)
And I get the following error:
could not convert string to float: ''
You can use or; given a string s, s or 0 will evaluate to 0 if s is empty:
s = ''
print(float(s or 0)) # 0.0
s = '123'
print(float(s or 0)) # 123.0
This happens because (in python) x or y returns x if x is true, and y if x is false. Since an empty string is "falsy", '' or 0 is equal to 0.
I want to link an object to its parent at frame 40 and unlink at frame 80. I feel like it should be something like this:
o.parent = p
o.keyframe_insert(data_path="???", index=-1, frame=40)
o.parent = None
o.keyframe_insert(data_path="???", index=-1, frame=80)
Thanks!
After googling and experimenting I have come up with a small example of how to set and unset (aka influence) a Child Of constraint.
import bpy
def add_frame(oArgObject, sArgType, dArgFrame, sArgName):
if sArgType == 'location':
oArgObject.keyframe_insert(data_path='location', index=-1, frame=dArgFrame)
elif sArgType == 'influence':
oArgObject.keyframe_insert(data_path='constraints["'+sArgName+'"].influence', frame=dArgFrame)
else:
print('Unrecognized frame option: ' + sArgType)
def add_parent(oArgChild, oArgParent, bArgScale):
sName = 'Child' + oArgChild.name + 'Parent' + oArgParent.name
if sName in oArgChild.constraints:
print('Constraint ' + sName + ' exists')
else:
oConst = oArgChild.constraints.new(type = 'CHILD_OF')
oConst.name = sName
oConst.target = oArgParent
oConst.use_scale_x = bArgScale[0]
oConst.use_scale_y = bArgScale[1]
oConst.use_scale_z = bArgScale[2]
print('Constraint ' + sName + ' added')
def set_influence(oArgChild, oArgParent, dArgFrame, dArgInfluence):
sName = 'Child' + oArgChild.name + 'Parent' + oArgParent.name
if sName in oArgChild.constraints:
index = 0
while oArgChild.constraints[index].name != sName:
index += 1
o = oArgChild.constraints[index]
o.influence = 1 - dArgInfluence
add_frame(oArgChild, 'influence', dArgFrame-1, sName)
o.influence = dArgInfluence
add_frame(oArgChild, 'influence', dArgFrame, sName)
else:
print('No constraints exists for object ' + oArgChild.name)
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
bpy.ops.mesh.primitive_cube_add(size = 1, location = (1,0,0))
oParent1 = bpy.context.object
oParent1.scale = (0.5, 1.0, 0.5)
oParent1.name = 'Parent1'
add_frame(oParent1, 'location', 10, 'n/a')
oParent1.location.x += 4
add_frame(oParent1, 'location', 50, 'n/a')
bpy.ops.mesh.primitive_cube_add(size = 1, location = (0,1,0))
oParent2 = bpy.context.object
oParent2.scale = (1.0, 0.5, 0.5)
oParent2.name = 'Parent2'
add_frame(oParent2, 'location', 60, 'n/a')
oParent2.location.y += 4
add_frame(oParent2, 'location', 100, 'n/a')
bpy.ops.mesh.primitive_cube_add(size = 1, location = (0,0,1))
oChild = bpy.context.object
oChild.scale = (0.5, 0.5, 1.0)
oChild.name = 'Child'
add_frame(oChild, 'location', 5, 'n/a')
add_parent(oChild, oParent1, (True,True,True))
add_parent(oChild, oParent2, (False,False,False))
set_influence(oChild, oParent1, 20, 1)
set_influence(oChild, oParent1, 40, 0)
set_influence(oChild, oParent2, 70, 1)
set_influence(oChild, oParent2, 90, 0)
First
Error:
ERROR 2011-04-22 23:25:15,513 __init__.py:395] unbound method put() must be called with Movie instance as first argument (got nothing instead)
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 515, in __call__
handler.get(*groups)
File "C:\Users\Jimenez\workspace\elmovieplace\src\script/crawl.py", line 86, in get
getImdbData(year, findPatGamma, findPatGamma2)
File "C:\Users\Jimenez\workspace\elmovieplace\src\script/crawl.py", line 66, in getImdbData
movie.put()
TypeError: unbound method put() must be called with Movie instance as first argument (got nothing instead)
crawl.py:
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from urllib2 import urlopen
from Classes import Movie
import re
def getImdbData(year, findPatGamma, findPatGamma2):
templistone = []
templisttwo = []
listIterator = []
listIterator[:] = range(len(findPatGamma))
for gi in listIterator:
deltaUrl = findPatGamma[gi]
deltaPage = urlopen(deltaUrl).read()
print deltaUrl
simpleone = (re.findall(re.compile("""id='hmovie'.*[^\n]src='|"(.*[^\n])'|".*[^\n]"""),deltaPage))[0]
templistone.append(simpleone)
simpletwo = (re.findall(re.compile("<title>Project Free TV - (.*) video</title>"),deltaPage))[0]
templisttwo.append(simpletwo)
movie = Movie
url = 'http://www.imdbapi.com/?plot=full&t=' + findPatGamma2[0] + '&y=' + year
imdbPage = urlopen(url).read()
imdbValues, = re.findall(re.compile('{"Title":"(.*)","Year":"(.*)","Rated":"(.*)","Released":"(.*)","Genre":"(.*)","Director":"(.*)","Writer":"(.*)","Actors":"(.*)","Plot":"(.*)","Poster":"(.*)","Runtime":"(.*)","Rating":"(.*)","Votes":"(.*)","ID":"(.*)","Response":"(.*)"}'),imdbPage)
movie.title = imdbValues[0]#done
if imdbValues[1] == 'N/A':
movie.rated = ''
else:
movie.rated = imdbValues[2]#done
if imdbValues[3] == 'N/A':
movie.releaseDate = 'jan 1 1990'
else:
movie.releaseDate = imdbValues[3]
if imdbValues[4] == 'N/A':
movie.tags = [];
else:
movie.tags = re.findall(re.compile('(\w*[^\s|,])'),imdbValues[4])#done
if imdbValues[5] == 'N/A':
movie.diector = ''
else:
movie.director = imdbValues[5],#done
if imdbValues[6] == 'N/A':
movie.writer = ''
else:
movie.writer = imdbValues[6],#done
if imdbValues[7] == 'N/A':
movie.actors = []
else:
movie.actors = re.findall(re.compile('(\w*[^\s|,])'),imdbValues[7])#done
if imdbValues[8] == 'N/A':
movie.description = ''
else:
movie.description = imdbValues[8]#done
if imdbValues[9] == 'N/A':
movie.pic = ''
else:
movie.pic = imdbValues[9]#done
if imdbValues[10] == 'N/A':
movie.length = 0
else:
movie.length = (60 * int((re.findall(re.compile('(.*) hrs .* mins'),imdbValues[10]))[0])) + int((re.findall(re.compile('.* hrs (.*) mins'),imdbValues[10]))[0])#done
movie.uniqueID = imdbValues[13]#done
movie.hostNames = templisttwo
movie.hostUrls = templistone
movie.put()
return
class MyHandler(webapp.RequestHandler):
def get(self):
year = '2011'
betaUrl = 'http://www.free-tv-video-online.me/movies/' + year + '/'
betaPage = urlopen(betaUrl).read()
patFinderBeta = re.compile('<td width="97%" class="mnlcategorylist"><a href="(.*)">')
findPatBeta = re.findall(patFinderBeta,betaPage)
listIteratorBeta = []
listIteratorBeta[:] = range(len(findPatBeta))
for bi in listIteratorBeta:
gammaUrl = betaUrl + findPatBeta[bi]
gammaPage = urlopen(gammaUrl).read()
patFinderGamma = re.compile('<a href="(.*[^\n])" target="_blank" class="mnllinklist">')
findPatGamma = re.findall(patFinderGamma,gammaPage)
patFinderGamma2 = re.compile('<meta name="keywords"content="(.*)">')
findPatGamma2 = re.findall(patFinderGamma2,gammaPage)
getImdbData(year, findPatGamma, findPatGamma2)
ip = self.request.remote_addr
template_values = {
'username': ip,
}
self.response.out.write(template.render('template\crawl.html', template_values))
def main():
app = webapp.WSGIApplication([(r'.*', MyHandler)],debug=True)
wsgiref.handlers.CGIHandler().run(app)
if __name__ == '__main__':
main()
Classes.py:
from google.appengine.ext import db
class Movie(db.Model):
title = db.StringProperty()
hostNames = db.StringProperty()
hostUrls = db.StringListProperty()
releaseDate = db.DateProperty()
uniqueID = db.StringProperty(default='000000')
playcount = db.IntegerProperty(default='0')
length = db.IntegerProperty()
rated = db.StringProperty()
description = db.StringProperty()
tags = db.StringListProperty()
director = db.StringProperty()
writer = db.StringProperty()
actors = db.StringProperty()
pic = db.StringProperty()
I've looked around some post (in other words I've been searching for a day now) but I cant figure out what I'm doing wrong.
'O' and by the way, encase my question didn't make that apparent, I'm new at this.
Change it from
movie = Movie
to
movie = Movie()
You need to actually make an instance of the Movie class, which is what Movie() does. (The key word in the error message you got was "Movie instance".)