Python Flask cookie consent - python

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.

Related

Add multiple checkout buttons for multiple events on same page Eventbrite

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.

How to dynamically re-render template?

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){ });
});

Unknown code being added to HTML template when running local server

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.

Check if the user's input is valid

Users are entering their address and age. When the find button is hit, it will display the inputs. However, for the case where input is not valid, I would like to add an error message.
How do I check if the input is not valid and gives an error message? I want my error message to be on the same page as where values are input. The code does not work correctly.
<div class = "Information">
<h2>Your Infomation</h2>
<form action="" method=post>
if (error){
<p id="error"><strong></strong>{{error}}
}
<div id = "address">
<label>address</label>
<input type=text name=address value="{{request.form.address}}">
</div>
<div id = "age">
<label>age</label>
<input type=text name=age value="{{request.form.age}}">
</div>
<div class = "Input">
<a href="/results">
<button type = "button" class = "btn btn-primary" value="find" >Find!</button>
</a>
</div>
</form>
</div>
#app.route('/results',methods=['GET','POST'])
def result():
error = None;
if request.method == 'POST':
if request.form['age'] != '14':
error='You did not enter proper values'
return render_template('template.html',error=error)
You need to use proper Jinja syntax to render templates:
{% if error %}<p id="error">{{ error }}</p>{% endif %}
Beyond that, the button you've added to your form doesn't actually submit the form, as you've given it the "button" type rather than the "submit" type and have wrapped it in an anchor for some reason. Replace the contents of <div class="Input"> with:
<button type="submit" class="btn btn-primary" value="find">Find!</button>

Page redirect to next page

I am using a map api in my app.For selecting marker, button named "Add marker" and "Refresh map" for refresh map.I am facing the here.
After saving the data,the save button will redirect to next page.in my case,both "Add marker","Refresh map" both are doing the save buttons job and if i press "Add marker" instead of showing marker,page gets redirect to next page.this is happening after using the </form>.see my template here,
<form method="POST" action="/member/where/" >
{% csrf_token %}
<td colspan="2" class="incident-type" style="padding-left:25px">
{% for location in locationList%}
{% if location.parent_location_id == None %}
<h1>{{location.title}}</h1>
{% endif %}
{% endfor %}
<p>
<span class="map_buttons" >{% include "buttons/refreshmap.html" %}</span> <span class="map_buttons" style="margin-left:20px;">{% include "buttons/addmarker.html" %} </span>
</p>
<p id=ir-nextbtn>{% include "buttons/next.html" %}</a></form></p>
refreshmarker.html
<button type="submit" title="Refresh map" class="map_buttons button_style">Refresh map</button>
addmarker.html
<button type="submit" title="Add marker" class="map_buttons button_style">Add marker</button>
Need clarification about this issue.
The problem is because both the buttons are of type submit, when you click either of the buttons, the form gets submitted. as a result, the page gets redirected oto action of the form i.e. /member/where/
try this:-
keep the refresh as it is,
<button type="submit" title="Refresh map" class="map_buttons button_style">Refresh map</button>
and add
<button onClick=somefuntion(this)' title="Add marker" class="map_buttons button_style">Add marker</button>
and let some function do the needfull
<script>
function somefuntion(button){
// your code
document.forms[0].submit() // this will submit your form
}
</script>

Categories