this is in additional scripts section of shopify and im trying to send a pixel event for certain rules. i have pricing rules in place which work fine but this one isnt saving(assuming because it's wrong
{% for line in checkout.line_items %}
{% assign found_collection = false %}
{% for collection in line.product.collections %}
{% if collection.title == 'Collection NAME' %}
{% assign found_collection = true %}
{% endif %}
{% endfor %}
{% if found_collection == true %}
Related
I'm trying to create a way to export the HTML table to xlsx, but I have a large amount of data in the queries. So I need to use pagination with Paginator so the browser doesn't load the data all at once and end up causing TimeOut. But when applying the Paginator and exporting, it only exports what is on the current page. Any suggestions to improve this code, such as creating a loop so that it can export all pages?
View function:
def export_project_data(request, pk):
if str(request.user) != 'AnonymousUser': # só vai ter acesso se for diferente de AnonymousUser
individuals_list = Individual.objects.filter(Project=pk)
traps = Sample_unit_trap.objects.filter(Project=pk)
page = request.GET.get('page', 1)
paginator = Paginator(individuals_list, 1000)
try:
individuals = paginator.page(page)
except PageNotAnInteger:
individuals = paginator.page(1)
except EmptyPage:
individuals = paginator.page(paginator.num_pages)
path_info = request.META['PATH_INFO']
context = {
'individuals': individuals,
'pk': pk,
'traps': traps,
'header': 'export_project_data',
'path_info': path_info
}
return render(request, 'inv/index.html', context)
HTML paginator code:
<div class="table-div">
{% if individuals.has_other_pages %}
<ul class="pagination pagination-sm">
{% if individuals.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in individuals.paginator.page_range %}
{% if individuals.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if individuals.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
</div>
{% endif %}
Javascript html to xlsx code:
<script>
function html_table_to_excel(type)
{
var data = document.getElementById('data');
var file = XLSX.utils.table_to_book(data, {sheet: "Dados_Ecológicos"});
XLSX.write(file, { bookType: type, bookSST: true, type: 'base64' });
XLSX.writeFile(file, 'file.' + type);
}
const export_button = document.getElementById('export_button');
export_button.addEventListener('click', () => {
html_table_to_excel('xlsx');
});
</script>
The problem is fairly complex. Let's say the input of my function is a string. The input can contain the following keywords:
"{% if some_condition %}" (Start)
"{% endif %}" (End)
"{% else if some_other_condition %}" (Optional)
"{% else %}" (Optional)
Along with these keywords, the input may also contain any other string. The conditions are basically just names of variables, so within a string before parsing, they are just strings (any valid string is acceptable as a variable name).
Here's what the function is meant to do:
Take the input and look for start and end tag pairs.
When found, look inside the contents between the start tag and end tag.
If the content contains "{% else if <any_condition> %}" OR "{% else %}", then do nothing.
Otherwise, add the "{% else %}<div class='empty'>Empty</div>" string right at the end of the content.
So for clarity, here is an example input:
{% if username %}
<p>Hello {{ username }}</p>
{% endif %}
{% if score > 10 %}
<p>You are doing great.</p>
{% else if score > 50 %}
<p>You are freaking amazing!</p>
{% endif %}
<p>This is your <strong>awesome</strong> profile page.</p>
{% if not email %}
<p>Please consider setting your email address</p>
{% endif %}
{% if balance > 0 %}
<p>You are ready to go!</p>
{% else %}
<p>No balance</p>
{% endif %}
And the output would be the following:
{% if username %}
<p>Hello {{ username }}</p>
{% else %}<div class="empty">Empty</div>{% endif %}
{% if score > 10 %}
<p>You are doing great.</p>
{% else if score > 50 %}
<p>You are freaking amazing!</p>
{% endif %}
<p>This is your <strong>awesome</strong> profile page.</p>
{% if not email %}
<p>Please consider setting your email address</p>
{% else %}<div class="empty">Empty</div>{% endif %}
{% if balance > 0 %}
<p>You are ready to go!</p>
{% else %}
<p>No balance</p>
{% endif %}
In short, if the contents inside the if block doesn't have a conditional, then the extra string is appended right before the closing tag. Hope that makes sense. I know it's a lot to ask for, but could someone just get me started with this in the right direction? I'm not very good with regex using JavaScript, and it's basically kicking my ass. Thanks for any help!
I would do like the following. Flag "g" is global, "m" is multiline and "s" is "dotall" mode which means that "." can grab "\n". I grab all the inputs, replace them, see if there's "else if" or "else" therefore replace "{% endif %}" with "{% else %}" plus what you wanted plus "{% endif %}".
input.replace(
/{% if.*?%}.*?{% endif %}/gms,
match =>
(!/(else if|else)/.test(match))
? match.replace(
/{% endif %}/,
'{% else %}<div class="empty">Empty</div>{% endif %}'
)
: match
);
/*{% if username %}
<p>Hello {{ username }}</p>
{% else %}<div class="empty">Empty</div>{% endif %}
{% if score > 10 %}
<p>You are doing great.</p>
{% else if score > 50 %}
<p>You are freaking amazing!</p>
{% endif %}
<p>This is your <strong>awesome</strong> profile page.</p>
{% if not email %}
<p>Please consider setting your email address</p>
{% else %}<div class="empty">Empty</div>{% endif %}
{% if balance > 0 %}
<p>You are ready to go!</p>
{% else %}
<p>No balance</p>
{% endif %}*/
I'm building a web app using the Django framework. I'm attempting to use some JavaScript to disable a button that users can press to submit a text-based review.
The JavaScript in the listing.js file looks as follows:
document.addEventListener('DOMContentLoaded', function () {
hide_submit_review_button();
});
// Hide the 'Submit Review'button until the user begins typing a review
// Prevent the user from typing more than 100 characters
function hide_submit_review_button() {
var submit_review_button = document.getElementById('submit-review-button');
if (submit_review_button !== null) {
document.getElementById('submit-review-button').disabled = true;
document.getElementById('review-contents').onkeyup = () => {
if ((document.getElementById('review-contents').value.length > 0 &&
document.getElementById('review-contents').value.length <= 100 )) {
document.getElementById('submit-review-button').disabled = false;
} else {
document.getElementById('submit-review-button').disabled = true;
}
};
}
}
In my listing.html file, I identify the review-contents and submit-review-button. Here's the code:
{% extends "layout.html" %}
{% load static %}
{% block body %}
{% if user.is_authenticated %}
<form action="{% url 'review' listing.id %}" method="POST">
{% csrf_token %}
<input type="text" class="form-control" name="review" id="review-contents" placeholder="Write a review...">
<input class="btn btn-primary mt-1" type="submit" id="submit-review-button" value="Submit Review">
</form>
{% endif %}
{% endblock %}
{% block script %}
{% if user.is_authenticated %}
{{ block.super }}
<script src="{% static 'listing.js' %}"></script>
{% endif %}
{% endblock %}
An example of a page where the button appears is: http://127.0.0.1:8000/listings/7
And, here is what the urls.py file looks like (if it matters):
urlpatterns = [
path('', views.index, name='index'),
path('listings/<int:listing_id>', views.listing, name='listing'),
]
Can anyone see why this button doesn't disable?
Thanks!
The problem resulted from not having the following in the header tag in the layout.html file:
{% block script %}
{% endblock %}
I have a page that redirects users after clicking a submit button successfully to the homepage.
I want to display an indicator like this:
under the navigation bar of the homepage after being redirected back to it from the submit button.
How can I do that? excuse me I'm new to web development.
I believe you can create a response in flask that redirects and also sets a cookie. Something like
from flask import make_response
response = make_response(redirect('/homepage'))
response.set_cookie('show_success_flash', 'true')
return response
Then, on your JS side you can read the cookie, and if it's true, show the message. Then, you can either remove the cookie when dismissing the flash message or remove it after a setTimeout. Something like:
// homepage.js
const cookie = import 'js-cookie'
if (cookie.get('show_success_flash') {
const successFlash = document.getElementById('success_flash_message')
if (successFlash.style.display === 'none') {
successFlash.style.display = 'block'
}
}
Flask supports flashed messages. https://flask.palletsprojects.com/en/1.1.x/patterns/flashing/
In my opinion, this is better than using a cookie to display temporary popups.
So to set a flashed message, you do the following:
#app.route('/sample')
def sample():
if successCheck()
flash('You were successfully logged in')
return redirect("/index")
And in the template, to retrieve the flashed message, you do this:
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
You can also use categories:
# Route
flash(u'Invalid password provided', 'error')
# Template
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul class=flashes>
{% for category, message in messages %}
<li class="{{ category }}">{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
Or this template option:
# Template
{% with errors = get_flashed_messages(category_filter=["error"]) %}
{% if errors %}
<div class="alert-message block-message error">
<a class="close" href="#">×</a>
<ul>
{%- for msg in errors %}
<li>{{ msg }}</li>
{% endfor -%}
</ul>
</div>
{% endif %}
{% endwith %}
am getting this error trying to set a blog category page
NoReverseMatch at /blog/
Reverse for 'category_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['blog\/category\-detail\/(?P[-a-zA-Z0-9_]+)$']
Here is my url.py
from django.urls import path,include
from .import views
urlpatterns = [
path('blog/',views.post_list,name="post_list"),
path('blog/post-detail/<slug:slug>',views.post_detail,name="post_detail"),
path('blog/category-detail/<slug:slug>',views.category_detail,name="category_detail"),
]
views.py
from django.shortcuts import render,get_object_or_404
from.models import Post,Category
# Create your views here.
def post_list(request):
object_list=Post.objects.all()
context={
'object_list': object_list,
}
return render(request,"blog.html",context)
def post_detail(request,slug=None):
post=get_object_or_404(Post,slug=slug)
context={
'post':post,
}
return render(request,"post_detail.html",context)
def category_detail(request,slug=None):
category=get_object_or_404(Category,slug=slug)
post=Post.objects.filter(category=category,status='Published')
context={
'category':category,
'post':post,
}
return render(request,"category_detail.html",context)
blog.html
{% for obj in object_list %}
{% if obj.status == 'Published' %}
<article>
<div class="embed-responsive embed-responsive-16by9">
<img src="images/blog1.jpg" alt="" />
</div>
<div class="post-content">
<h2>{{obj.title}}</h2>
<div>
{{obj.created}} Author {{obj.user}} <h4>{{obj.Category}}</h4>
<hr/>
<p>{{obj.body}}</p>
<a class="mtr-btn button-navy ripple" href= "{% url 'post_detail' obj.slug %}">Continue reading →</a><br>
</div>
</article>
{% endif %}
{% endfor %}
category_detail.html
{% extends "base.html" %}
{% load static %}
{% block seo_title %}{{category.seo_title}}{% endblock %}
{% block seo_description %}{{category.seo_description}}{% endblock %}
{% block Content %}
<h2>{{category.title}}</h2>
<p>{{category.description}}</p>
{% for item in post %}
{{item.title}}
{{item.body|truncatechars:50}}
{% endfor %}
{% endblock Content %}
NOTE THE OTHER VIEWS.PY ARE WORKING FINE JUST THE category_detail function
As the error said, the argument is missing here. Maybe you need to change {% url 'category_detail' slug=post.Category.slug %} with {% url 'category_detail' slug=obj.category.slug %} because I do not see any post variable reference in the blog.html template.
update
You have not shared your Model codes, but I am assuming your Post Model has Foreign Key to Category Model and it looks like Category=models.ForeignKey(Category). So you need to update the view like this:
def category_detail(request,slug=None):
category=get_object_or_404(Category,slug=slug)
post=Post.objects.filter(Category=category,status='Published')