python code error for movie project "TypeError: this constructor takes no arguments" - python-2.7

I am working on a code project for Udacity and I get these 2 errors I dont get I have attached the pictures. One error is with parenthesis and when I remove the parenthesis I get an error on the code saying invalid syntax.
import webbrowser
class Movie():
valid_ratings = ["G", "R", "PG-13", "R"]
def _init_(self, movie_title, movie_storyline, poster_image,
trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url)
import fresh_tomatoes
import media
toy_story = media.Movie("Toy Story",
"A story of a boy and his toys come to life",
"http://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg",
"http://www.youtube.com/watch?v=vwyZH85NQC4")
The_devils_double = media.Movie("The_devils_double",
"The story of the son of sadam hussain's body double",
"https://upload.wikimedia.org/wikipedia/en/4/4c/The_Devil%27s_Double.jpg",
"https://www.youtube.com/watch?v=2-MsGEWFiYg",)
Movie_300 = media.Movie("300",
"300 spartans vs an amry of persians",
"https://upload.wikimedia.org/wikipedia/en/5/5c/300poster.jpg",
"https://www.youtube.com/watch?v=wDiUG52ZyHQ")
Ratatouille = media.Movie("Ratatouille",
"A rat is a chef in paris",
"https://upload.wikimedia.org/wikipedia/en/5/50/RatatouillePoster.jpg",
"https://www.youtube.com/watch?v=c3sBBRxDAqk")
Star_Wars_Episode_III = media.Movie("Star_Wars_Episode_III",
"Akin Skywalker goes dark",
"https://upload.wikimedia.org/wikipedia/en/9/93/Star_Wars_Episode_III_Revenge_of_the_Sith_poster.jpg",
"https://www.youtube.com/watch?v=5UnjrG_N8hU")
Office_Space = media.Movie("Office_Space ",
"A movie about how work sucks",
"https://upload.wikimedia.org/wikipedia/en/8/8e/Office_space_poster.jpg",
"https://www.youtube.com/watch?v=kwQziVIzDeg")
#movies = [toy_story, The_devils_double, 300, Ratatouille, Star_Wars_Episode_III , Office_Space ]
fresh_tomatoes.open_movies_page(movies)
print(media.Movie.valid_ratings)
import webbrowser
import os
import re
# Styles and scripting for the page
main_page_head = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fresh Tomatoes!</title>
<!-- Bootstrap 3 -->
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap-theme.min.css">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<style type="text/css" media="screen">
body {
padding-top: 80px;
}
#trailer .modal-dialog {
margin-top: 200px;
width: 640px;
height: 480px;
}
.hanging-close {
position: absolute;
top: -12px;
right: -12px;
z-index: 9001;
}
#trailer-video {
width: 100%;
height: 100%;
}
.movie-tile {
margin-bottom: 20px;
padding-top: 20px;
}
.movie-tile:hover {
background-color: #EEE;
cursor: pointer;
}
.scale-media {
padding-bottom: 56.25%;
position: relative;
}
.scale-media iframe {
border: none;
height: 100%;
position: absolute;
width: 100%;
left: 0;
top: 0;
background-color: white;
}
</style>
<script type="text/javascript" charset="utf-8">
// Pause the video when the modal is closed
$(document).on('click', '.hanging-close, .modal-backdrop, .modal', function (event) {
// Remove the src so the player itself gets removed, as this is the only
// reliable way to ensure the video stops playing in IE
$("#trailer-video-container").empty();
});
// Start playing the video whenever the trailer modal is opened
$(document).on('click', '.movie-tile', function (event) {
var trailerYouTubeId = $(this).attr('data-trailer-youtube-id')
var sourceUrl = 'http://www.youtube.com/embed/' + trailerYouTubeId + '?autoplay=1&html5=1';
$("#trailer-video-container").empty().append($("<iframe></iframe>", {
'id': 'trailer-video',
'type': 'text-html',
'src': sourceUrl,
'frameborder': 0
}));
});
// Animate in the movies when the page loads
$(document).ready(function () {
$('.movie-tile').hide().first().show("fast", function showNext() {
$(this).next("div").show("fast", showNext);
});
});
</script>
</head>
'''
# The main page layout and title bar
main_page_content = '''
<body>
<!-- Trailer Video Modal -->
<div class="modal" id="trailer">
<div class="modal-dialog">
<div class="modal-content">
<a href="#" class="hanging-close" data-dismiss="modal" aria-hidden="true">
<img src="https://lh5.ggpht.com/v4-628SilF0HtHuHdu5EzxD7WRqOrrTIDi_MhEG6_qkNtUK5Wg7KPkofp_VJoF7RS2LhxwEFCO1ICHZlc-o_=s0#w=24&h=24"/>
</a>
<div class="scale-media" id="trailer-video-container">
</div>
</div>
</div>
</div>
<!-- Main Page Content -->
<div class="container">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Fresh Tomatoes Movie Trailers</a>
</div>
</div>
</div>
</div>
<div class="container">
{movie_tiles}
</div>
</body>
</html>
'''
# A single movie entry html template
movie_tile_content = '''
<div class="col-md-6 col-lg-4 movie-tile text-center" data-trailer-youtube-id="{trailer_youtube_id}" data-toggle="modal" data-target="#trailer">
<img src="{poster_image_url}" width="220" height="342">
<h2>{movie_title}</h2>
</div>
'''
def create_movie_tiles_content(movies):
# The HTML content for this section of the page
content = ''
for movie in movies:
# Extract the youtube ID from the url
youtube_id_match = re.search(
r'(?<=v=)[^&#]+', movie.trailer_youtube_url)
youtube_id_match = youtube_id_match or re.search(
r'(?<=be/)[^&#]+', movie.trailer_youtube_url)
trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match
else None)
# Append the tile for the movie with its content filled in
content += movie_tile_content.format(
movie_title=movie.title,
poster_image_url=movie.poster_image_url,
trailer_youtube_id=trailer_youtube_id
)
return content
def open_movies_page(movies):
# Create or overwrite the output file
output_file = open('fresh_tomatoes.html', 'w')
# Replace the movie tiles placeholder generated content
rendered_content = main_page_content.format(
movie_tiles=create_movie_tiles_content(movies))
# Output the file
output_file.write(main_page_head + rendered_content)
output_file.close()
# open the output file in the browser (in a new tab, if possible)
url = os.path.abspath(output_file.name)
webbrowser.open('file://' + url, new=2)

Your init method has single underscores. It needs to have double underscores before and after "init".
def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
Also, you're missing a comma when you create the Movie_300 object. It should look like this (with a comma after the wikimedia link):
Movie_300 = Movie("300",
"300 spartans vs an amry of persians",
"https://upload.wikimedia.org/wikipedia/en/5/5c/300poster.jpg",
"https://www.youtube.com/watch?v=wDiUG52ZyHQ")
As an aside, the convention to name variables in Python is to use all lowercase.

Related

ApexCharts.js Line Chart - Display percent from total in tooltip

I want to display percent instead of an integer.
Now it simply shows the value as integer when hovering on the data point of the chart (the tooltip).
I think I need to set in the formatter formula like this:
let test = value / SUM(all_values)
return test.toFixed(0) + '%'
But, I could not find it in their documentation, the best I found is this one which always gives me 100%, per every data point:
tooltip: {
y: {
formatter: function(value, opts) {
let percent = opts.w.globals.seriesPercent[opts.seriesIndex][opts.dataPointIndex];
return percent.toFixed(0) + '%'
}
}
}
You're right that you'll need to use the tooltip formatter, but the array you're using to get the percentage values isn't correct.
If you log the values opts.w.globals.seriesPercent you'll find that it's all 100's:
[[100, 100, 100, ..., 100]]
(I suspect this might be because it's intended to be used with other chart types.)
You can still get the percentage though, it'll just need to be worked out.
Using your same method to format the tooltip, but getting the values from opts.series instead:
tooltip: {
y: {
formatter: function(value, opts) {
const sum = opts.series[0].reduce((a, b) => a + b, 0);
const percent = (value / sum) * 100;
return percent.toFixed(0) + '%'
},
},
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="app/app.js"></script>
<script>
let apiLabels = [];
let apiData = [];
let currentTimestamp = (Math.floor(Date.now() / 1000)).toString();
//use this URL for daily fetch
//let url = "https://aave-api-v2.aave.com/data/rates-history?reserveId=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb480xb53c1a33016b2dc2ff3653530bff1848a515c8c5&resolutionInHours=24&from="+currentTimestamp;
let url = "https://aave-api-v2.aave.com/data/rates-history?reserveId=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb480xb53c1a33016b2dc2ff3653530bff1848a515c8c5&resolutionInHours=24&from=1639813032";
// months list
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// fetch from api
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
let myData = JSON.parse(this.responseText);
console.log(myData);
for (let i = 0; i < myData.length; i++) {
//let formedDate = (myData[i]['x']['year']+'-'+myData[i]['x']['month']+'-'+myData[i]['x']['date']).toString();
let formedDate = monthNames[myData[i]['x']['month']] + ' ' + myData[i]['x']['date'];
console.log(formedDate);
let formedLiquidData = (myData[i]['liquidityRate_avg'] * 100).toFixed(2);
console.log(formedLiquidData+"%");
apiLabels.push(formedDate);
apiData.push(formedLiquidData);
}
const data = {
labels: apiLabels,
datasets: [
{
label: "USDC",
borderColor: "rgb(180,11,107)",
data: apiData
}
]
};
const config = {
type: "line",
data: data,
options:{
scales: {
y: {
ticks: {
callback: function (value, index, values) {
return value + '%';
}
}
},
},
},
};
const myChart = new Chart(document.getElementById("myChart"), config);
}
});
xhr.open(
"GET",
url
);
xhr.send();
</script>
</div>
<div id="app"></div>
<title>brew</title>
<style>
body {
background-color: white;
}
.center-form {
width: 80%;
margin: auto;
}
#title {
color: teal;
text-align: center;
}
.waitlist {
position: relative;
z-index: 3;
width: 146px;
height: 30px;
margin-top: 60px;
border-style: solid;
border-width: 1px;
border-color: #081852;
background-color: transparent;
box-shadow: -10px 10px 0 0 #081852;
color: #081852;
font-size: 12px;
line-height: 30px;
font-weight: 400;
text-align: center;
letter-spacing: 0.21px;
position: fixed;
right: 3%;
top: -5%;
}
.waitlist-button {
display: inline-block;
padding: 9px 15px;
background-color: #3898EC;
color: white;
border: 0;
line-height: inherit;
text-decoration: none;
cursor: pointer;
border-radius: 0;
}
.box-prices {
padding: 20px;
width: 200px;
height: auto;
color: #000;
/* background-color: #fff; */
border: 4px solid #1c1c53;
border-radius: 2px;
}
.dropbtn {
background-color: navy;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {
background-color: #ddd;
}
.dropdown:hover .dropdown-content {
display: block;
}
.dropdown:hover .dropbtn {
background-color: #0b95f1;
}
footer {
display: flex;
justify-content: space-between;
}
.myChart {
width: 50%;
height: 40px;
}
/* Decorative */
a {
text-decoration: none;
color: #555;
}
footer {
background-color: #82cdf8;
padding: 20px 40px;
}
.right {
float: left;
text-align: center;
}
.article {
color: white;
}
</style>
</head>
<body>
<img src="https://uploads-ssl.webflow.com/61768faf04d20bf3487b5a2a/6176a6363e64b8d84e32d0b7_brew-icon-256px-v2.png"
loading="eager" width="55" height="55" alt="Brew" class="img-logo" position="absolute" top="-3%" left="7;">
<!-------------- title------------------------>
<div class="container">
<div class="row">
<div class="col-md-12 mt-2">
<h1 style="color: #1c98">
Stablecoin Deposits on Aave
</h1>
<a data-w-id="14f1dfb2-926f-581f-7faa-3f62171b1db3" href="" class="waitlist waitlist-button">Join the
waitlist</a>
</div>
</div>
</div>
<!------------------------AAVE PRICE ------------>
<div class="container">
<div class="row mt-5">
<div class="col-md-6">
<div class="aave-prices">
<p>AAVE PRICE</p>
<p>$172.8</p>
<p>16%</p>
</div>
</div>
<!------------------------AAVE DESCRIPTION ------------>
<div class="col-md-6">
<h1>What is AAVE ?</h1>
<p>Aave is an open source and non-custodial liquidity protocol for earning
interest on deposits and borrowing assets.</p>
</div>
</div>
<!------------------------AAVe CHAIN ------------>
<div class="row">
<div class="col-md-12 mt-3">
<button class="dropbtn">CHAIN</button>
<div class="dropdown-content">
Polygon
Ethereum
Avalance
</div>
</div>
</div>
</div>
<!------graph----->
<div>
<canvas id="myChart" height="50" weidth="50"></canvas>
</div>
<!-- calculator -->
<div class="container mt-5" style="border: 1px solid black; border-radius: 5px;">
<div class="row">
<div class="col-md-12">
<h1 id="title">How Much You Can Earn ?</h1>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6">
<form>
<div class="form-group mt-2">
<label class="form-group">Amount</label>
<input class="form-control mt-2" type="text" id="principal" placeholder="$">
</div>
<div class="form-group mt-2">
<label class="form-group">Interest rate: 4%</label>
</div>
<div class="form-group mt-2">
<label class="form-group">Compound Freequency: Daily</label>
</div>
<div class="form-group mt-2">
<label class="form-group">Payout Freequency: Monthly</label>
</div>
<button class="btn btn-block btn-info mt-3" type="button" onclick="calculate()">Calculate</button>
</form>
</div>
<div class="col-md-6">
<form style="padding-top: 70px;">
<div class="form-group mt-2">
<label class="form-group">Interest rate: 5%</label>
</div>
<div class="form-group mt-2">
<label class="form-group">Compound Freequency: Daily</label>
</div>
<div class="form-group mt-2">
<label class="form-group">Payout Freequency: Monthly</label>
</div>
</form>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6">
<h5 class="total">Result USD</h5>
<h1 id="USD"></h1>
</div>
<div class="col-md-6">
<h5 class="total">Result USDT</h5>
<h1 id="USDC"></h1>
</div>
</div>
</div>
<!-- calculator end -->
<div>
<canvas id="myChart_subbagain" height="50" weidth="50" top="80%"></canvas>
</div>
<!----footer-->
<div class="col-md-12 mt-5">
<footer>
<div class="col-md-6">
<img src="/dawnload.png" alt="" width="150">
</div>
<div class="col-md-6">
<section class="right">
Join Brew Today
<article>USDC is not a legal tender recognised by US or any other government. Unlike a bank account, your
deposit is not insured. While Brew will make every effort to ensure that your deposit earn the best interest
rates in the most secure way possible, please note that any investment entails risk. Interest Rates are
subject to change anytime as per the market conditions.</article>
</section>
</div>
</footer>
</div>
</body>
<script type="text/javascript">
function calculate() {
var principle = 0;
var interest = 5 / 100;
var numberOfPeriod = 12;
var time = 10;
var CI = 0;
principle = document.getElementById("principal").value;
// CI = ((p * (1 + i) ^ n) - p);
CI = principle * (1 + interest / numberOfPeriod) ^ (numberOfPeriod * time);
document.getElementById("USD").innerHTML = CI;
document.getElementById("USDC").innerHTML = CI;
}
</script>
<!------cal graph-->
</html>

Django rendering a number as a 5-stars rating

I'm building a rating system for my website. It's currently working well but I would like to improve the esthetical aspect of the system. I would like to be able to take the rating from the database and display it as a 5-stars rating. Also, if it's not overly complicated, I would like to be able to click on stars to record the rating in the database, rather than writing a number.
I'm quite new to web development. In particular, I have no experience with javascript (I only did tutorials found on internet), which I think is required to implement the functionality I'm searching for, so please gives me a little example with your response in order to make me able to understand.
For rendering the rating as stars, I have no idea how to do it. For recording the rating as stars, I thought about two solutions :
1) Using django star-ratings but I don't think I have the capabilities required to understand how it works. I already made a post to ask for help and examples about this app but I received no help so I guess I should forget this.
2) Using a form with some appropriate widget to render an IntegerInput as a 5-stars rating.
For the second solution, I already have the code, I now need a widget to replace 'Stars' in the code below but I'm not sure how to do it. Can someone help me ?
models.py
class Avis(models.Model):
note = models.IntegerField()
forms.py
class AvisForm(forms.ModelForm):
class Meta:
model = Avis
fields = ['note']
widgets = {'note': forms.NumberInput(attrs={'class': 'Stars'})}
labels = {'note': 'Note /5'}
hmtl for recording
<form method="post" action="">
{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper form-group">
{{ field.label_tag }}
{{ field }}
</div>
{% endfor %}
<input type="submit" class="btn btn-lg btn-outline-primary btn-block btn-login text-uppercase font-
weight-bold mb-2" value="Envoyer mon avis" />
</form>
hmtl for displaying
{{ avis.note }}
Thanks in advance !
EDIT (my code so far for the ratings storing) :
views.py
def avis(request, id): # view for displaying and storing the form
commande = get_object_or_404(Commande, id=id)
if request.method == "POST":
form = AvisForm(request.POST)
if form.is_valid():
avis = form.save(commit = False)
avis.commande = commande
avis.save()
commande.has_avis = True
commande.save()
if commande.plat.chef.nb_avis==0:
commande.plat.chef.rating = avis.note
else:
commande.plat.chef.rating = (commande.plat.chef.rating*commande.plat.chef.nb_avis + avis.note)/(commande.plat.chef.nb_avis + 1)
commande.plat.chef.nb_avis += 1
commande.plat.chef.save()
messages.success(request, 'Votre avis a été correctement envoyé !')
return redirect(mes_commandes)
else:
form = AvisForm()
return render(request, 'actualites/avis.html', locals())
def avis2(request, id): # view for recording the rating
avis = get_object_or_404(Avis, id=id)
rating = request.POST.get('rating')
avis.note = rating
avis.save()
messages.success(request, 'Votre avis a été correctement envoyé !')
return redirect(mes_commandes)
html
<form method="post" action="">
{% csrf_token %}
{% for field in form %}
<div class="fieldWrapper form-group">
{{ field.label_tag }}
{{ field }}
</div>
{% endfor %}
<input type="submit" class="btn btn-lg btn-outline-primary btn-block btn-login text-uppercase font-weight-bold mb-2" value="Envoyer mon avis" />
</form>
<div class="rating rating2">
★
★
★
★
★
</div>
<script>
$(".rating a").on('click', function(e){
let value = $(this).data('value');
$.ajax({
url: "{% url 'avis2' %}",
type: 'POST',
data: {'rating': value},
success: function (d){
// some processing
}
})
});
</script>
forms.py
class AvisForm(forms.ModelForm):
class Meta:
model = Avis
fields = ['commentaire']
widgets = {'commentaire': forms.Textarea(attrs={'class': 'form-control'})}
I will try to answer your both of the question. For getting the rating, your can render stars and add a JS click event to that.
Code (HTML, CSS) source: https://codepen.io/GeoffreyCrofte/pen/jEkBL
$(".rating a").on('click', function(e){
let value = $(this).data('value');
$.ajax({
url: "some_url",
type: 'POST',
data: {'rating': value},
success: function (d){
// some processing
}
})
});
.rating {
width: 300px;
margin: 0 auto 1em;
font-size: 45px;
overflow:hidden;
}
.rating input {
float: right;
opacity: 0;
position: absolute;
}
.rating a,
.rating label {
float:right;
color: #aaa;
text-decoration: none;
-webkit-transition: color .4s;
-moz-transition: color .4s;
-o-transition: color .4s;
transition: color .4s;
}
.rating label:hover ~ label,
.rating input:focus ~ label,
.rating label:hover,
.rating a:hover,
.rating a:hover ~ a,
.rating a:focus,
.rating a:focus ~ a {
color: orange;
cursor: pointer;
}
.rating2 {
direction: rtl;
}
.rating2 a {
float:none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rating rating2">
★
★
★
★
★
</div>
For Rendering the rating, you need to calculate the value first. You need to determine the number of person who rated 5, 3, ... 1 stars. Lets say there are 100's 5 star rating, 70 * 4 star, 50 * 3 star, 30 * 2 and 20 * 1 star rating. So you can determine rating by:
sum of rating / total rating
So it will be (100 * 5 + 70 * 4 + 50 * 3 + 30 * 2 + 20 * 1) / 100 + 70 + 50 + 30 + 20
So the final rating will be: 3.74
To get the width percentage: (3.74 * 100) / 5 = 74.8
Here 5 refers to total number of stars, here I am assuming that rating will be based on the scale of 5.
For rendering you will need different HTML and CSS.
Code source: https://codepen.io/Bluetidepro/pen/GkpEa
.star-ratings-css {
unicode-bidi: bidi-override;
color: #c5c5c5;
font-size: 25px;
height: 25px;
width: 100px;
margin: 0 auto;
position: relative;
padding: 0;
text-shadow: 0px 1px 0 #a2a2a2;
}
.star-ratings-css-top {
color: #e7711b;
padding: 0;
position: absolute;
z-index: 1;
display: block;
top: 0;
left: 0;
overflow: hidden;
}
.star-ratings-css-bottom {
padding: 0;
display: block;
z-index: 0;
}
.star-ratings-sprite {
background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/2605/star-rating-sprite.png") repeat-x;
font-size: 0;
height: 21px;
line-height: 0;
overflow: hidden;
text-indent: -999em;
width: 110px;
margin: 0 auto;
}
.star-ratings-sprite-rating {
background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/2605/star-rating-sprite.png") repeat-x;
background-position: 0 100%;
float: left;
height: 21px;
display: block;
}
<div class="star-ratings-css">
<div class="star-ratings-css-top" style="width: 74.8%">
<span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></div>
<div class="star-ratings-css-bottom"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></div>
</div>
You need to pass width from your view and in the HTML, you need to access it.
<div class="star-ratings-css-top" style="width: {{ width }}%">. I tried these code snippet, working for me and should work for you as well :)

Use stripe token to charge credit card with stripe element

I'm really stuck in this subject and maybe someone can help me out. I can always generate a token with stripe successfully but somehow my charge function doesn't wan't to work. I'm using the stripe element from their official documentation.
How can I find out where I have to search for the mistake because I don't get any error from the code. In the stripe dashboard I can see the generated tokens, that's why I think until this point there is everything right but I guess my mistake is in the view function. More precise I think the view function doesn't get the generated token from the javascript. Many thanks for your help in advance!
stripe_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
{% load static %}
<link rel="stylesheet" href="{% static 'css/stripe.css' %}">
<title>Document</title>
</head>
<body>
<div id="collapseStripe" class="wrapper">
<script src="https://js.stripe.com/v3/"></script>
<form action="" method="post" id="payment-form">
{% csrf_token %}
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element" class="StripeElement StripeElement--empty">
<div class="__PrivateStripeElement" style="margin: 0px !important; padding: 0px !important; border: none !important; display: block !important; background: transparent !important; position: relative !important; opacity: 1 !important;"><iframe frameborder="0" allowtransparency="true" scrolling="no" name="__privateStripeFrame4" allowpaymentrequest="true" src="https://js.stripe.com/v3/elements-inner-card-bfbabea0af3ed365b5fe9ce78692fd3c.html#style[base][color]=%2332325d&style[base][fontFamily]=%22Helvetica+Neue%22%2C+Helvetica%2C+sans-serif&style[base][fontSmoothing]=antialiased&style[base][fontSize]=16px&style[base][::placeholder][color]=%23aab7c4&style[invalid][color]=%23fa755a&style[invalid][iconColor]=%23fa755a&componentName=card&wait=false&rtl=false&keyMode=test&origin=https%3A%2F%2Fstripe.com&referrer=https%3A%2F%2Fstripe.com%2Fdocs%2Fstripe-js%2Felements%2Fquickstart&controllerId=__privateStripeController1" title="Secure payment input frame" style="border: none !important; margin: 0px !important; padding: 0px !important; width: 1px !important; min-width: 100% !important; overflow: hidden !important; display: block !important; height: 19.2px;"></iframe><input class="__PrivateStripeElement-input" aria-hidden="true" aria-label=" " autocomplete="false" maxlength="1" style="border: none !important; display: block !important; position: absolute !important; height: 1px !important; top: 0px !important; left: 0px !important; padding: 0px !important; margin: 0px !important; width: 100% !important; opacity: 0 !important; background: transparent !important; pointer-events: none !important; font-size: 16px !important;"></div>
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
</div>
<button>Submit Payment</button>
</form>
</div>
<div id="stripe-token-handler" class="is-hidden">Success! Got token: <span class="token"></span></div>
{% load static %}
<script src="{% static 'js/stripe.js' %}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function toggleDisplay() {
var x = document.getElementById("collapseStripe");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
};
</script>
</body>
</html>
views.py
import stripe
stripe.api_key = settings.STRIPE_SECRET_KEY
def charge (request):
publishKey = settings.STRIPE_PUBLISHABLE_KEY
if request.method == 'POST':
try:
token = request.POST['stripeToken']
charge = stripe.Charge.create(
amount=999,
currency='usd',
description='Example charge',
source=token,
)
return redirect(request, 'registration/stripe_form.html')
except stripe.CardError as e:
message.info(request, "Your card has been declined.")
return render(request, 'registration/stripe_form.html')
stripe.js
var stripe = Stripe('pk_test_');
// Create an instance of Elements.
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Create an instance of the card Element.
var card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
}
});
});
// Submit the form with the token ID.
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
var successElement = document.getElementById('stripe-token-handler');
document.querySelector('.wrapper').addEventListener('click', function() {
successElement.className = 'is-hidden';
});
// Not in demo.
function stripeTokenHandler(token) {
successElement.className = '';
successElement.querySelector('.token').textContent = token.id;
}

MVC - What can I do if I do not want my Email field display error when regular expression validation fails?

I'm creating an MVC page that uses Kendo validation.
I have the following Model:
public class ForgotPasswordModel
{
[Required(ErrorMessage = " ")]
public string UserName { get; set; }
[Required(ErrorMessage = " ")]
[EmailAddress(ErrorMessage = " ")]
public string Email { get; set; }
public string PhoneNumber { get; set; }
[Required(ErrorMessage = " ")]
public string Code { get; set; }
}
I do not want my view to show Error Message for the Email field. I want it to show only exclamation sign when validation fails.
Currently I have the following code in my View:
#model Site.Models.ForgotPasswordModel
#{
ViewBag.Title = "Forgot Password";
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/kendo/kendo.common-material.min.css" rel="stylesheet" />
<link href="~/Content/kendo/kendo.custom.css" rel="stylesheet" />
<link href="~/Content/kendo/custom.css" rel="stylesheet" />
<script src="~/Scripts/kendo/kendo.all.min.js"></script>
<script src="~/Scripts/kendo/kendo.aspnetmvc.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<style>
input[type=text]::-ms-clear {
display: none;
}
input[type=password]::-ms-reveal {
display: none;
}
.errMsg {
font-weight: bolder;
color: red;
}
span#UserName_validationMessage, span#Email_validationMessage,span#Code_validationMessage {
display: inline-block;
width: 160px;
text-align: left;
border: 0;
padding: 0;
margin: -20px;
background: none;
box-shadow: none;
color: red;
}
.k-invalid-msg {
display: none;
}
</style>
</head>
<body>
<div>
</div>
<div style="margin-top: 20px;">
<div style="margin: 0 auto; width: 940px; height: 409px; background-image: url('../../Content/images/finance-globe.jpg');"/>
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "ForgotPasswordForm" }))
{
<div style="margin: 0 auto; margin-top: 20px;">
<table id="ForgotPassword" style="margin: 0" auto;">
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.UserName, new { htmlAttributes = new { #class = "form-control k-textbox checkError", placeholder = "username" } })</td>
</tr>
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.Email, new { htmlAttributes = new { #class = "form-control k-textbox checkError", placeholder = "email" } })</td>
</tr>
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.PhoneNumber, new { htmlAttributes = new { #class = "form-control k-textbox", placeholder = "phone number" } })</td>
</tr>
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.Code, new { htmlAttributes = new { #class = "form-control k-textbox checkError", placeholder = "code" } })</td>
</tr>
</table>
</div>
}
</div>
</body>
</html>
<script>
$(document).ready(function () {
$("#ForgotPasswordForm").kendoValidator();
});
</script>
The Model and View produce the following:
enter image description here
I do not want "Email is not valid" message to be displayed in case of regular expression validation fails.
I just need an exclamation sign.
How can I do that?
For your email field you can try adding data-email-msg attribute, which is way to customize the validation message for wrong email field value.
For ex: If you want to display a blank message for wrong value for email id you can do something like:
<input type="email" name="email" id="email" name="email" data-email-msg="">
And if you want to customize the required field validation message too, then you can add an another attribute data-required-msg as below:
<input type="email" name="email" id="email" name="email" data-email-msg="" data-required-msg="">

Input not being displayed

I have an input field. When the user clicks it some javascript converts the text to a Raphael JS library variable. I want to put each letter into a Raphael variable called string followed by a \n. When the user clicks on the button nothing is displayed. Can someone help me fix this?...
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
var string = "";
function animate() {
var txt = document.getElementById("words").value;
var splittxt = txt.split("");
var i;
for (i = 0; i < splittxt.length; i++) {
var string = splittxt[i] + "\n\n";
}
}
</script>
<style type="text/css">
#letters
{
text-align:center;
margin-left:10px;
width:25px;
float:left;
text-shadow:10px 5px 1px #4D4D4D;
filter:DropShadow(Color=#4D4D4D, OffX=10, OffY=5);
font-weight:bold;
}
</style>
</head>
<body>
Text: <input type="text" id="words" />
<input type="button" value="Animate" onclick="animate()" />
<div id='letters'></div>
<div id="draw-here-raphael" style="height: 200px; width: 400px; margin-top:0px; background-color:blue;">
</div>
<div id="elps" style="ma
rgin-left:100px;"/>
<script type="text/javascript"> //all your javascript goes here
var r = new Raphael("draw-here-raphael");
var string = r.text(50,50, string);
</script>
</body>
</html>
Instead of setting the variable string, you want add to it. Also, there were quite a few other updates I made to your excerpt...
Setting variables to reserved words can also cause a lot of problems.
http://jsfiddle.net/fN9Me/
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
var alpha = "";
var something = "";
var r = "";
var txt = "";
var splittxt = "";
$(function() {
r = new Raphael("draw-here-raphael");
$("#animate").click(function() {
txt = $("#words").val();
splittxt = txt.split("");
var i;
for (i = 0; i < splittxt.length; i++) {
something += splittxt[i] + "\n\n";
}
alpha = r.text(50, 50, something);
});
});
</script>
<style type="text/css">
#letters
{
text-align:center;
margin-left:10px;
width:25px;
float:left;
text-shadow:10px 5px 1px #4D4D4D;
filter:DropShadow(Color=#4D4D4D, OffX=10, OffY=5);
font-weight:bold;
}
</style>
</head>
<body>
Text: <input type="text" id="words" value="" />
<input id="animate" type="button" value="Animate" />
<div id='letters'></div>
<div id="draw-here-raphael" style="height: 200px; width: 400px; margin-top:0px; background-color:blue;">
</div>
<div id="elps" style="margin-left:100px;"/>
</body>
</html>
Update:
To remove the previous text, it is just a matter of utilizing the Raphael remove function. Also we have to reset the variable something
if (alpha) alpha.remove();
http://jsfiddle.net/fN9Me/1/
You're not actually displaying anything. This line:
document.getElementById("letters").innerHTML + splittxt[i] + "<br>";
needs to be something like:
document.getElementById("letters").innerHTML += splittxt[i] + "<br>";
The value of the words input is blank => when you call the split method var splittxt = txt.split(""); the splittxt has a length == 0, and therefore the body of the for statement is never executed.