How to add multiple checkout buttons for multiple events on the same page?
<script src="https://www.eventbrite.com/static/widgets/eb_widgets.js"></script>
<script type="text/javascript">
var exampleCallback = function () {
console.log('Order complete!');
};
var getEventID = function(){
var value = document.getElementById('eventID').value;
return value;
};
window.EBWidgets.createWidget({
widgetType: 'checkout',
eventId: getEventID,
modal: true,
modalTriggerElementId: 'checkout_btn',
onOrderComplete: exampleCallback,
});
</script>
HTML Here
{% for event in data.events %}
<form id="form_id">
{% csrf_token%}
<div class="center">
<div class="w3-card-4" style="width:100%;">
<header class="w3-container w3-blue" >
<h1>{{event.name.text}}</h1>
</header>
<div class="w3-container" style="background-color: #ddd;">
<p>{{event.description.text}}</p>
Event ID: <input type="hidden" id="eventID" name="eventID" value="{{event.id}}"><br>
Capcity: {{event.capacity}}
<button id="checkout_btn" class="button" type="button">Buy Tickets!</button>
</div>
</div>
</form>
{% endfor %}
I am showing multiple events in Django and trying to fetch the event id in script code. It works for one event when I provide a hardcoded value.
Any help will be appreciated!
Found the solution, but don't know if it is a good one or not (But working for me):
{% for event in data.events %}
<form id="form_id">
<!-- checkout widget START-->
<script src="https://www.eventbrite.com/static/widgets/eb_widgets.js"></script>
<script type="text/javascript">
var exampleCallback = function () {
console.log('Order complete!');
};
window.EBWidgets.createWidget({
widgetType: 'checkout',
eventId: '{{event.id}}',
modal: true,
modalTriggerElementId: 'checkout_btn-{{event.id}}',
onOrderComplete: exampleCallback,
});
</script>
<!-- checkout widget END -->
{% csrf_token%}
<div class="center">
<header class="w3-container w3-blue">
<h1>{{event.name.text}}</h1>
</header>
<p>{{event.description.text}}</p>
Event ID: <input type="hidden" id="eventID" name="eventID" value="{{event.id}}">{{event.id}}
<br>
Capcity: {{event.capacity}}
<br>
Starting: {{event.start.local}}
<br>
Ending: {{event.end.local}}
</div>
<button id="checkout_btn-{{event.id}}" class="button" type="button">Buy Tickets!</button>
</form>
{% endfor %}
Took the script inside the loop and provided a unique id to the button as checkout_btn-{{event.id}}. It will become checkout_btn-xxxxxxxxxxx121(event ID retrieve from {{event.id}}). Similarly provide the same button id in the script as modalTriggerElementId: 'checkout_btn-{{event.id}}',
and provided eventId: '{{event.id}}', in place of eventId: getEventID. Now it can distinguish between each event.
Related
I want to set a banner that asks for permission to store cookies on my website(because GDPR). I've tried like this:
HTML:
{% block cookies %}
{% if cookies_check %}
{% else %}
<div class="fixed-bottom p-4" id="cookie-consent-container">
<div class="toast bg-dark text-white w-100 mw-100" role="alert">
<div class="toast-body p-4 d-flex flex-column">
<h4>Cookie Warning</h4>
<p>
This website stores data such as cookies to enable site functionality including analytics and personalization. By using this website, you automatically accept that we use cookies.
</p>
<div class="ml-auto">
<button type="button" class="btn btn-outline-light mr-3" id="btnDeny">
Deny
</button>
<button type="button" class="btn btn-light" id="btnAccept">
Accept
</button>
</div>
</div>
</div>
</div>
<script>
var fn = function () {
document.cookie = "cookie_consent=true";
document.getElementById('cookie-consent-container').hidden = true;
};
document.getElementById('btnAccept').onclick = fn;
</script>
{% endif %}
{% endblock cookies %}
and jinja2
#app.context_processor
def inject_template_scope():
injections = dict()
print(injections)
def cookies_check():
value = request.cookies.get('cookie_consent')
print(value)
return value == 'true'
injections.update(cookies_check=cookies_check)
return injections
The prints are for debugging. The problem is that the list is always empty and the banner is never showing. What should I do to make this work? Does that mean that the site is not generating any cookie to begin with? If so how can I add a cookie when the site is loaded?
A cookie can be added,read,deleted using document.cookie
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
By default cookie delete after browser is closed.
Currently I am trying to create a dynamic filter for listing model objects in a template. Here is the django view:
def view_data(request):
text = request.GET.get('text')
persons = None
if text:
try:
persons = models.Person.objects.get(code__regex=text)
except models.Person.DoesNotExist:
pass
return render(request, 'view_data.html',
{'persons': persons if not isinstance(persons, models.Person) else [persons]})
The related part from the template:
<div class="jumbotron row">
<form>
<label>Alanyok szűrése</label>
<input id="filter" type="text" placeholder="Keresett alany">
</form>
</div>
<div class="row">
<div class="col-4">
<div class="list-group" id="list-tab" role="tablist">
{% for person in persons %}
<a class="list-group-item list-group-item-action" id="list-{{person.code}}" data-toggle="list" href="#" role="tab" aria-controls="{{person.code}}">{{person.code}}</a>
{% endfor %}
</div>
</div>
<div class="col-8">
<div class="visualisation content">
<div class="canvas_div">
<canvas id="Canvas1" width="540" height="250" style="border:1px solid #202020;">
</canvas>
</div>
</div>
</div>
</div>
The input field with filter id has a callback on keyup event which sends a request to django with the content of the input field which is used in the view for query.
Here is the callback:
$( "#filter" ).keyup(function() {
$.get("", {text: $('#filter').val()});
});
When I checked it with Pycharm debugger, the render returns the correct html but on the client side the html doesn't change. How to re-render with the new object list?
Take a part of your html code that you want to replace and place it inside a new html file like this:
new_html:
<div class="list-group" id="list-tab" role="tablist">
{% for person in persons %}
<a class="list-group-item list-group-item-action"
id="list-{{person.code}}" data-toggle="list"
href="#" role="tab" aria-controls="{{person.code}}">
{{person.code}}
</a>
{% endfor %}
</div>
now in your view replace the name of your old html file ( that you are rendering ) with the new html file like this:
return render(request, 'new_html.html',
{'persons': persons if not isinstance(persons,models.Person) else [persons]})
and now in your ajax you can dynamically load this new_html like this :
$( "#filter" ).keyup(function() {
$.get("",
{text: $('#filter').val()},
function(data){
$( "#list-tab" ).replaceWith( data );
}
);
});
You are not doing nothing with the returned data. Add a callback function in the get method call. You get the response from the server in the first argument. Use that to hide and show contents on the page. Or you can even replace elements in the DOM. See jquery.replaceWith.
$( "#filter" ).keyup(function() {
$.get("", {text: $('#filter').val()}, function(response){ });
});
I was able to show a map on a single page using django-leaflet. In another page, I am trying to show two (or more) maps in page but I couldn't figure out how.
For showing map in a single page:
<div class="card">
{% leaflet_map "main" callback="map_init" %}
</div>
<script type="text/javascript">
function map_init(map, options) {
// get point lat and lon
var lon = "{{ project.longitude }}";
var lat = "{{ project.latitude }}";
// zoom to point & add it to map
map.setView([lat, lon], 12);
L.marker([lat, lon]).addTo(map);
}</script>
Above works fine as long as one map needs to be shown. However I am not sure how I can modify above to support multiple maps.
I have started jsfiddle page here (which is kind of blank), not sure if it's going to helpful.
What I am trying is to fill the 'img-top' div in the html below:
var locations = [
{"lat":27.988098,"lng":86.924925},
{"lat":27.679535,"lng":83.507020}
]
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card-columns m-5">
<div class="card">
<div class="card-header">Location A </div>
<div class="img-top" id="map-1" style="height:200px"></div>
<div class="card-body">
Some information of A
</div>
</div>
<div class="card">
<div class="card-header">Location B </div>
<div class="img-top" id="map-2" style="height:200px"></div>
<div class="card-body">
Some information of B
</div>
</div>
</div>
Not very dry, but does the below work?
<div class="card">
{% leaflet_map "map_1" callback="map_init_1" %}
</div>
<div class="card">
{% leaflet_map "map_2" callback="map_init_2" %}
</div>
<script type="text/javascript">
function map_init(map, lat, lon) {
// zoom to point & add it to map
map.setView([lat, lon], 12);
L.marker([lat, lon]).addTo(map);
}
function map_init_1(map) {
map_init(map, "{{ project1.latitude }}", "{{ project1.longitude }}")
}
function map2_init_2(map) {
map_init(map, "{{ project2.latitude }}", "{{ project2.longitude }}")
}
</script>
It seems to me that django-leaflet addresses the most simple cases. You might need to write your logic in javascript using leaflet directly to achieve what you're trying to do.
You can see what django-leaflet does when you call {% leaflet_map ... %}:
https://github.com/makinacorpus/django-leaflet/blob/master/leaflet/templates/leaflet/_leaflet_map.html
Updated JS Fiddle: https://jsfiddle.net/cdfrn53L/
EDIT:
With for loops in Django template:
{% for location in locations %}
<div class="card">
{% leaflet_map location.div_id callback=location.callback %}
</div>
{% endfor %}
<script type="text/javascript">
function map_init(map, lat, lon) {
// zoom to point & add it to map
map.setView([lat, lon], 12);
L.marker([lat, lon]).addTo(map);
}
{% for location in locations %}
function {{ location.callback }}(map) {
map_init(map, "{{ location.lat }}", "{{ location.lon }}")
}
{% endfor %}
</script>
Provided your view builds a list of locations:
locations = [
{'lat': 27.988098, 'lng': 86.924925, 'div_id': 'map-1', 'callback': 'callback_1'},
{'lat': 27.679535, 'lng': 83.507020, 'div_id': 'map-2', 'callback': 'callback_1'}
]
You can build div_id and callback values based on the location list index.
This is how I was able to display the two (or more) maps dynamically in a div.
<script type="text/javascript">
items_json.forEach(item => {
let map = L.map(item.id + "-map").setView([item.fields.latitude, item.fields.longitude], 10);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
});
</script>
In HTML this <div class="img-top" id="{{id}}-map" style="height:200px"></div> gets filled in with the map.
Here's JS Fiddle: https://jsfiddle.net/droidxn/w7d5nqps/10/
I was building a profile picture feature, it was working fine so I left it for a while, probably a week. I came back to it and ran the local server, but when I do there's a few lines that appear in the console. But do not exist on the source file.
Source file:
<script type='text/javascript'>
Dropzone.options.myDropzone = {
autoProcessQueue : false,
paramName: 'uploaded_image',
dictDefaultMessage: "Drag and drop files or click here to upload picture",
init: function() {
var submitButton = document.querySelector("#submitBtn")
myDropzone = this;
submitButton.addEventListener("click", function() {
myDropzone.processQueue();
});
// Automatically overwrites file so the user can only upload one
this.on("addedfile", function() {
document.getElementById('submitBtn').style.visibility = "visible";
});
this.on('addedfile', function(){
if (this.files[1]!=null){
this.removeFile(this.files[0]);
}
});
}
};
</script>
<!-- Modal -->
<div id="picModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close"></span>
<form action="{% url 'profile_test' %}" method='POST' enctype="multipart/form-data" class="dropzone" id="my-dropzone">{% csrf_token %}
<!-- submit button stays hidden by default, until user selects a picture -->
<button id='submitBtn' type='submit' class='pic-submit-button' style='visibility: hidden;'> Submit </button>
<input id='submit-all' type='file' name='uploaded_image'/>
{{form}}
</form>
</div>
</div>
Now the code I'm seeing when I run the server is only a few lines, and it's in the HTML that creates the modal:
<!-- Modal -->
<div id="picModal" class="modal" style="display: block;">
<!-- Modal content -->
<div class="modal-content">
<span class="close"></span>
<form action="/api/profile_test/" method="POST" enctype="multipart/form-data" class="dropzone dz-clickable" id="my-dropzone"><input type="hidden" name="csrfmiddlewaretoken" value="WDMihPq0zDhDQGaWxSFYyvxjtmxUxsBMpAzcDqVxDGUZj11O8wtqbCfCie1m81Tf">
<!-- submit button stays hidden by default, until user selects a picture -->
<button id="submitBtn" type="submit" class="pic-submit-button" style="visibility: hidden;"> Submit </button>
*****<input id="submit-all" type="file" name="uploaded_image">
<label for="id_user">User:</label><select name="user" id="id_user">
<option value="" selected="">---------</option>
<option value="2">Brian</option>
<option value="3">Charles</option>
</select>
<label for="id_img">Img:</label><input type="file" name="img" required="" id="id_img">
<div class="dz-default dz-message"><span>Drag and drop files or click here to upload picture</span></div></form>
</div>
</div>*****
The last chunk of code I put stars around is the code that is unknown to me. The Django project I cloned was using gulp, I talked to my friends and they said that it may have something to do with it, maybe it's doing something with Dropzone.js?. But why would it inject a random dropdown menu listing users in Django? I didn't use gulp myself because I just wanted to develop the feature, but that may have been a mistake.
Possibly the
{{form}}
is causing this issue.
Sorry guys, maybe this has been asked before. But I googled around for several days and still cannot solve the problem. I am developing a chatting system using Google App Engine with Python. I would like the user to enter her/his message and click "Submit" button. That action will trigger an Ajax post function "addMsg()" to POST the message to class Chat (URL: "/chat"), which will add the message to datastore. There is another Ajax function "updateMsg()" which will update the message list periodically.
The code works fine for message updating, however, I am not able to post the message correctly. Can anybody help me? Thanks. Here are my codes:
chat.html:
<p>
<form method="" action="">
<input type="text" name="message" size="60" /><br />
<input type="button" value="Submit" onclick="addMsg('message')" />
</form>
</p>
<div id="chatcontent"> </div>
<script>
function addMsg(message) {
$.ajax({
type: "POST",
url: "/chat",
data: {'message': message},
cache: false
});
}
</script>
<script>
$(document).ready(function() {
function updateMsg() {
$.ajax({
url: "/message",
cache: false,
success: function(returndata){
$("#chatcontent").html(returndata);
}
});
setTimeout(updateMsg, 4000);
}
updateMsg();
});
</script>
message.html:
{% for chat in chatlist %}
<p>
{{ chat.text }} ({{ chat.user.account }}) {{chat.created|date:"D d M Y" }}
</p>
{% endfor %}
chat.py:
# Called by URL "/chat"
class Chat(webapp2.RequestHandler):
def post(self):
message = self.request.get('message')
newchat = ChatMessage(user=self.session['userkey'], text=message, created=datetime.datetime.now())
newchat.put()
# Called by URL "/message"
class Message(webapp2.RequestHandler):
def get(self):
que = db.Query(ChatMessage).order('-created')
chatlist = que.fetch(limit=100)
render(self, 'message.html', {'chatlist': chatlist})
# Note: render() is a function to be imported, which is just a normal template rendering function. It works fine and is omitted here.
Chat.html
<p>
<input type="text" name="message" size="60" /><br />
<input type="button" value="Submit" onclick="addMsg()" />
</p>
<div id="chatcontent"> </div>
<script>
function addMsg() {
var message = $('input[name=message]').val();
$.ajax({
type: "POST",
url: "/chat",
data: {'message': message},
cache: false
});
}
</script>