Django admin add view popup dialog box - javascript

How can I pass in an extra GET parameter in the add view popup box in the Django admin?
Basically I have a + sign in a foreign key, and when I click on it, it opens a popup box to add a new object of that type.
The problem is that I am using some custom Ajax code in the popup box, and I need to find a way to update only the field that is opened the dialog box (assuming there might be other foreign key fields).
The only solution I can think of is to somehow pass in a GET parameter so that I know which field should be updated.
Any ideas? I just need a push in the right direction in order to complete this
Right now I am doing something like this to update the field. and I want to make this dynamic
if ($('#id_avatar').length) {
$('#id_avatar', opener.document).append($('<option selected="selected"></option>').attr('value', data.obj_id).text(data.obj__unicode__));
}
I guess I somehow reloading the select box in the original page could be an option since at this point its already saved in the database.

I ended up overriding the fieldsets in change_form.html. not sure if its the best approach but it seems to be working for me.
Now i can pass a source_field to know what field called the popup so i can later updated the proper field with Jquery
{% for fieldset in adminform %}
{# {% include "admin/includes/fieldset.html" %}#}
<fieldset class="module aligned {{ fieldset.classes }}">
{% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %}
{% if fieldset.description %}
<div class="description">{{ fieldset.description|safe }}</div>
{% endif %}
{% for line in fieldset %}
<div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}">
{% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %}
{% for field in line %}
<div{% if not line.fields|length_is:'1' %} class="field-box{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}>
{% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
{% if field.is_checkbox %}
{{ field.field }}{{ field.label_tag }}
{% else %}
{{ field.label_tag }}
{% if field.is_readonly %}
<p>{{ field.contents }}</p>
{% else %}
{% if field.field.name == 'avatar' %}
<select id="id_avatar" name="avatar">
<option value="" selected="selected">---------</option>
</select> <img src="/static/admin/img/icon_addlink.gif" width="10" height="10" alt="Add Another">
{% else %}
{{ field.field }}
{% endif %}
{% endif %}
{% endif %}
{% if field.field.help_text %}
<p class="help">{{ field.field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
</div>
{% endfor %}
</fieldset>
{% endfor %}

Related

How do I add links to variants of products in a product card (displayed on landing page and collections page) on Shopify?

On the landing page and collections page, below each product, I want the color variants to link to the variant with the color selected e.g. if I click on the red color, it takes me to the product page with the red variant selected. I managed to add the color variants but I don't know how to link them to the variants. The products also have sizes as they are clothes, so I want the XS size to be selected by default.
When the red variant is clicked, takes to the product page with variants with XS and Red selected.
When the black variant is clicked, takes to the product page with variants XS and Black selected.
When the black variant is clicked, takes to the product page with variants XS and White selected.
How do I dynamically add a link that redirects to the product page with XS + color clicked?
Source: https://cropshopboutique.com/
The code I have for the colors so far are:
color-option-row.liquid
<div class="product-option-row flex justify-between flex-column flex-row-ns tc tl-ns mb4">
<div class="option-values">
{% for value in option.values %}
{% assign radio_id = 'option-' | append: option_name | append: '-' | append: value | handleize %}
<a href="{{ product.url }}?variant={{ variant.id }}">
<label for="{{ radio_id }}">
{% if force_colors == true %}
{% include 'option-color' with color: value %}
{% else %}
{{ value }}
{% endif %}
</label>
</a>
{% endfor %}
</div>
</div>
color-variant-hover.liquid
{% assign has_multiple_variants = false %}
{% if product.variants.size > 1 %}
{% assign has_multiple_variants = true %}
{% endif %}
{% assign has_multiple_options = false %}
{% if product.options.size > 1 %}
{% assign has_multiple_options = true %}
{% endif %}
{% assign has_selected_variant = false %}
{% if product.selected_variant != nil %}
{% assign has_selected_variant = true %}
{% endif %}
{% if has_multiple_variants %}
{% include 'get-variants-with-quantity-json' with product: product %}
{% endif %}
{% assign can_add_to_cart = false %}
{% if has_selected_variant and product.selected_variant.available %}
{% assign can_add_to_cart = true %}
{% elsif has_multiple_variants == false and product.available %}
{% assign can_add_to_cart = true %}
{% endif %}
{% if has_multiple_options or has_multiple_variants %}
{% for option in product.options_with_values %}
{% assign option_name = 'option' | append: option.position %}
{% assign selected = false %}
{% if has_selected_variant %}
{% assign selected = product.selected_variant[option_name] %}
{% endif %}
{% assign default_variant = product.selected_or_first_available_variant %}
{% if option.name == 'Color' %}
<div class="option-colors">
{% include 'color-option-row' with option: option, option_name: option_name, selected: selected, force_colors: true %}
</div>
{% elsif option.name == 'Pattern' %}
<div class="option-patterns">
{% include 'color-option-row' with option: option, option_name: option_name, selected: selected, force_colors: true %}
</div>
{% else %}
<div class="dn">
{% include 'color-option-row' with option: option, option_name: option_name, type: 'select', selected: selected %}
</div>
{% endif %}
{% endfor %}
{% endif %}
<input class="js-variant-id" type="hidden" name="id" value="{{ default_variant.id }}">
featured-products.liquid
<div class="product-card fl w-50 w-25-l mb3 ph1 ph3-m ph3-l">
{% include 'product-card' %}
{% include 'color-variant-hover' %}
</div>
Try to update your color-option-row.liquid to the following:
<div class="product-option-row flex justify-between flex-column flex-row-ns tc tl-ns mb4">
<div class="option-values">
{% for value in option.values %}
{% assign radio_id = 'option-' | append: option_name | append: '-' | append: value | handleize %}
{%- for variant in product.variants -%}
{%- if variant.title contains value -%}
{%- assign productColorOptionURL = product.url | append: "?variant=" | append: variant.id -%}
{%- break -%}
{%- endif -%}
{%- endfor -%}
<a href="{{ productColorOptionURL }}">
<label for="{{ radio_id }}">
{% if force_colors == true %}
{% include 'option-color' with color: value %}
{% else %}
{{ value }}
{% endif %}
</label>
</a>
{% endfor %}
</div>
</div>

jQuery widgets not working for dynamically added formset forms

I have a form and a related formset in my view/template. For several fields I use widgets: Select2 and a calendar (date-picker) from django admin app.
I also use dynamic addition of formset forms.
When I render a template for the first time, all widgets work fine. But when I add new formset form, widgets of this new form don't work.
I've read existing questions on this kind of problem: 1, 2, 3, 4, but they either not applicable for me, or not helping (2 and 3), or may be I am just doing something wrong (most likely - I'm new to it).
Much appreciated for any tips.
HTML:
{% extends "docs/base.html" %}
{% load static %}
{% block extrahead %}
{{ block.super }}
{{ form_matter.media.css }}
<link href="/static/django_select2/select2.min.css" type="text/css" media="screen" rel="stylesheet">
{% endblock %}
{% block content %}
{% if mat_id == None %}
<form id="MatterForm" action="{% url 'matter_create_url' %}" enctype="multipart/form-data" method="post">
{% else %}
<form id="MatterForm" action="{% url 'matter_edit_url' mat_id=mat_id %}" enctype="multipart/form-data" method="post">
{% endif %}
{% csrf_token %}
<fieldset>
{% for field in form_matter %}
<div class="form-row">
{% if field.errors %}
<div>{{ field.errors }}</div>
{% endif %}
<label class="form-label">{{ field.label_tag }}</label>
<div class="form-input">{{ field }}</div>
</div>
{% endfor %}
<h3>RESOLUTIONS</h3>
<div id="form_set">
{{ formset_resolutions.management_form }}
{% for form in formset_resolutions %}
<div class="formset-form">
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
<div class="form-row">
{% if field.errors %}
<div>{{ field.errors }}</div>
{% endif %}
<label class="form-label">{{ field.label_tag }}</label>
<div class="form-input">{{ field }}</div>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
</fieldset>
<br>
<button class="btn" type="button" id="add_form" style="margin: 0 0 0 25px">ADD</button>
<button class="btn" type="submit" style="margin: 0 0 0 25px">SAVE</button>
<br><br><br>
<div id="empty_form" style="display:none">
<div class="formset-form">
{% for field in formset_resolutions.empty_form.visible_fields %}
<div class="form-row">
{% if field.errors %}
<div>{{ field.errors }}</div>
{% endif %}
<label class="form-label">{{ field.label_tag }}</label>
<div class="form-input">{{ field }}</div>
</div>
{% endfor %}
</div>
</div>
</form>
<script type="text/javascript">window.__admin_media_prefix__ = "{% static 'admin/' %}";</script>
<script type="text/javascript" src="/jsi18n/"></script>
<script type="text/javascript" src="/static/js/jquery.js"></script>
<script type="text/javascript" src="/static/django_select2/select2.min.js"></script>
<script>
$('#add_form').on('click', function() {
var form_idx = $('#id_resolution_set-TOTAL_FORMS').val();
$('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
$('#id_resolution_set-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
</script>
<script>$('div.form-row:has(label.form-label:has(label[for$="-DELETE"]))').css('background-color', '#ffc7c7')</script>
{{ form_matter.media.js }}
{% endblock content %}

jQuery not loading in Django admin homepage/dashboard, login and logout pages

I need to load a js file throught all django admin pages. Hence I copied the base.html file located in django/contrib/admin/templates/admin/ and added it to my templates folder under templates/admin/base.html. Added the js file under app_static/admin/js/ (location to my static files).
Next, I included the <script> tags inside the base.html under the {% block javascripts %} tags.
When I open the change_list and change_form pages, the js fires correctly. It does not fire in the homepage/dashboard, login and logout pages. Returns an error stating Uncaught ReferenceError: django is not defined. An error usually thrown when jQuery has not been initialized.
session_expiry.js
(function($){
console.log('js has been called');
})(django.jQuery);
base.html
{% load i18n static %}<!DOCTYPE html>
{% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %}
<html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" type="text/css" href="{% block stylesheet %}{% static "admin/css/base.css" %}{% endblock %}">
{% block extrastyle %}{% endblock %}
{% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% block stylesheet_rtl %}{% static "admin/css/rtl.css" %}{% endblock %}">{% endif %}
{% block extrahead %}{% endblock %}
{% block responsive %}
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0">
<link rel="stylesheet" type="text/css" href="{% static "admin/css/responsive.css" %}">
{% if LANGUAGE_BIDI %}<link rel="stylesheet" type="text/css" href="{% static "admin/css/responsive_rtl.css" %}">{% endif %}
{% endblock %}
{% block javascripts %}
<script type="text/javascript" src="{% static "admin/js/session_expiry.js" %}"></script>
{% endblock %}
{% block blockbots %}<meta name="robots" content="NONE,NOARCHIVE">{% endblock %}
</head>
{% load i18n %}
<body class="{% if is_popup %}popup {% endif %}{% block bodyclass %}{% endblock %}" data-admin-utc-offset="{% now "Z" %}">
<!-- Container -->
<div id="container">
{% if not is_popup %}
<!-- Header -->
<div id="header">
<div id="branding">{% block branding %}{% endblock %}</div>
{% block usertools %}
{% if has_permission %}
<div id="user-tools">
{% block welcome-msg %}
{% trans 'Welcome,' %}
<strong>{% firstof user.get_short_name user.get_username %}</strong>.
{% endblock %}
{% block userlinks %}
{% if site_url %}
{% trans 'View site' %} /
{% endif %}
{% if user.is_active and user.is_staff %}
{% url 'django-admindocs-docroot' as docsroot %}
{% if docsroot %}
{% trans 'Documentation' %} /
{% endif %}
{% endif %}
{% if user.has_usable_password %}
{% trans 'Change password' %} /
{% endif %}
{% trans 'Log out' %}
{% endblock %}
</div>
{% endif %}
{% endblock %}
{% block nav-global %}{% endblock %}
</div>
<!-- END Header -->
{% block breadcrumbs %}
<div class="breadcrumbs">
{% trans 'Home' %}
{% if title %} › {{ title }}{% endif %}
</div>
{% endblock %}
{% endif %}
{% block messages %}
{% if messages %}
<ul class="messagelist">{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message|capfirst }}</li>
{% endfor %}</ul>
{% endif %}
{% endblock messages %}
<!-- Content -->
<div id="content" class="{% block coltype %}colM{% endblock %}">
{% block pretitle %}{% endblock %}
{% block content_title %}{% if title %}<h1>{{ title }}</h1>{% endif %}{% endblock %}
{% block content %}
{% block object-tools %}{% endblock %}
{{ content }}
{% endblock %}
{% block sidebar %}{% endblock %}
<br class="clear">
</div>
<!-- END Content -->
{% block footer %}<div id="footer"></div>{% endblock %}
</div>
<!-- END Container -->
</body>
</html>
Could anyone point out what I might be missing. I am using Django 2.1.2.
django.jQuery is defined in django/contrib/admin/static/admin/js/jquery.init.js and situated on django/contrib/admin/static/admin/js/jquery.js. You need to load those js files in your template directly
<script type="text/javascript" src="/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>

How to filter by tag rather than by title

Newbie programmer looking for some advice on some code I am trying to learn to read and fix in hubSpot. I want to get the code to search blog posts by tags and not by just the title. Any advice would be appreciated. I will post the code below. I'd appreciate any explanation of what is going on with it as I have very little experience with databases. Thanks!
<div class="body-container-wrapper">
<div class="body-container container-fluid">
<div class="row-fluid-wrapper row-depth-1 row-number-1 ">
<div class="row-fluid ">
<div class="span12 widget-span widget-type-cell flush-rows" style="" data-widget-type="cell" data-x="0" data-w="12">
<div class="row-fluid-wrapper row-depth-1 row-number-2 ">
<div class="row-fluid ">
<div class="span12 widget-span widget-type-cell container" style="" data-widget-type="cell" data-x="0" data-w="12">
<div class="row-fluid-wrapper row-depth-1 row-number-3 ">
<div class="row-fluid ">
<div class="span12 widget-span widget-type-raw_jinja " style="" data-widget-type="raw_jinja" data-x="0" data-w="12">
{# Instead of trying to sort the contents directly, make a list of just event dates and post ids. #}
{% set events = utility.event_looper(contents, (topic or simple_list_page or blog_author))|split(',')|sort(simple_list_page or topic == 'past-events' or topic == 'webinar', True) %}
{% set months = utility.month_looper(contents, (topic or simple_list_page or blog_author))|split(',')|sort(simple_list_page or topic == 'past-events' or blog_author, True)|unique %}
{% set page_number = request.query_dict.page|int or 1 %}
{% set posts_per_page = 1000 if simple_list_page else 12 %}
{% set max_pages = (events|count / posts_per_page)|round(0, 'ceil') %}
{% if page_number > max_pages %}
{% set page_number = max_pages %}
{% endif %}
{% set offset = (page_number - 1) * posts_per_page %}
{% set base_url = group.absolute_url ~ '/' %}
{% if current_month %}
{% set topic = current_month %}
{% endif %}
{% if topic %}
{% set base_url = base_url ~ 'topic/' ~ topic %}
{% endif %}
{% if blog_author %}
{% set base_url = base_url ~ 'author/' ~ blog_author.slug %}
{% endif %}
{% if current_month %}
{% set topic = current_month %}
{% endif %}
{% set month_labels = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]%}
{% if is_listing_view %}
<div class="padded-section padded-section--half">
<div class="events-listing">
<div class="filters filters--blog">
<h3 class="filters__title">Explore Events</h3>
<div class="filters__controls">
{% set current_month = request.query_dict.month %}
{% if current_month or topic %}
View All
{% endif %}
<div class="filters__item filters__item--filter filters__item--filter--topics select-nav">
<span class="select-nav__label" title="Type">
Type
</span>
<div class="select-nav__options">
Webinar
Conference
</div>
</div>
{% unless current_month or topic %}
<div class="filters__item filters__item--filter filters__item--filter--topics select-nav">
<span class="select-nav__label" title="{{ topic_group.label_plural }}">
{% if current_month and month_labels[current_month] %}{{ current_month.label }}: {{ month_labels[current_month] }}{% else %}Months{% endif %}
</span>
<div class="select-nav__options">
{% for month in months %}
{% set year = month[0:4] %}
{% set month_value = month[4:6] %}
{% set month_index = month[4:6]|trim|int - 1 %}
{% set month_label = month_labels[month_index] %}
{{ month_label }} {{ year }}
{% endfor %}
</div>
</div>
{% endunless %}
{{ components.search_form('https://www.----.com/search', 'blog-search', current_search, 'filters__item filters__item--search', 'q') }}
</div>
</div>
{% if events %}
<div class="event-listing clearfix">
{% for event in events %}
{% set post_id = event|split(':', 2)|last %}
{% set content = blog_post_by_id(post_id) %}
{% if simple_list_page or (loop.index > offset and loop.index <= offset + posts_per_page) %}
{{ components.event_thumbnail_blog_post(content) }}
{% endif %}
{% endfor %}
</div>
<nav class="blog-listing__nav listing-nav">
{% if page_number > 1 %}
Previous
{% endif %}
{% if simple_list_page or topic or blog_author %}
View Upcoming
{% else %}
View Past Events
{% endif %}
{% endif %}
{% if page_number < max_pages %}
Next
{% endif %}
</nav>
{% else %}
<div class="events-listing__error">
<p><em>Couldn't find any upcoming events!</em></p>
{% if blog_author or topic %}
<p>View Upcoming</p>
{% endif %}
</div>
{% endif %}
{% endif %}
</div>
</div>
{% endif %}
</div><!--end widget-span -->
First off, it's an embedded javaScript file EJS if that helps you translate what's going on in there. A lot of it looks like variable setting and drop down menus.
But in general, you get information from a database through an API route. For example, the chunk where you can find other posts from the same author is through a GET route to yourSiteURL.com/author/edgar%20allen%20poe or a query search like yoursite.com/posts?tag='gothic' you would request these GET routes and receive data back.
I would check out the API docs for whatever database you're trying to connect with or see about setting up your own if this is only a template and you have to connect to your own.

Long loading Javascript (modal window)

On this site http://nashedom.ru there are JS scripts. Most are fast.
The modalka fancybox pages (for login users, in user cabinet, page объявления -> добавление объявления) are very slow. In Chrome loading is 25-28 seconds. In Firefox - 2,5 seconds.
The data is taken out of context.
HTML:
{% load hosts %}
<div class="b-header">
<div class="b-header__menu">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="b-menu">
<a>...</a>
<a>...</a>
<a>...</a>
<a>...</a>
<span class="b-menu__item btn_change-location">
<a href="#change-location" class="fancybox dashed">
{% if user.is_authenticated %}
View ads on site:
{% if user.districts.all.count > 1 %}
{% for district in user.districts.all %}
{% if forloop.last %}
<span>{{ district }}</span>
{% else %}
<span>{{ district }},</span>
{% endif %}
{% endfor %}
{% else %}
{% for district in user.districts.all %}
<span>{{ district }}</span>
{% endfor %}
{% endif %}
{% if user.regions.all.count > 1 %}
{% for region in user.regions.all %}
{% if forloop.last %}
<span>{{ region }}</span>
{% else %}
<span>{{ region }},</span>
{% endif %}
{% endfor %}
{% else %}
{% for region in user.regions.all %}
<span>{{ region }}</span>
{% endfor %}
{% endif %}
{% if user.cities.all.count > 1 %}
{% for city in user.cities.all %}
{% if forloop.last %}
<span>{{ city }}</span>
{% else %}
<span>{{ city }},</span>
{% endif %}
{% endfor %}
{% else %}
{% for city in user.cities.all %}
<span>{{ city }}</span>
{% endfor %}
{% endif %}
{% else %}
View ads on site:
{% endif %}
</a>
</span>
</div>
</div>
</div>
</div>
</div>
Templates modal window
{% load hosts %}
{% load widget_tweaks static %}
<div id="change-location">
<form action="{% host_url "setlocation" host "www" %}" method="post">
{% csrf_token %}
<div id="chose-city-wrap">
<div class="b-modal__title">Select your city</div>
<p>
<div class="b-modal__item">
<span>{{ location_form.country.label }}</span>
{{ location_form.country }}
</div>
</p>
<p>
<div class="b-modal__item">
<span>{{ location_form.districts.label }}</span>
{{ location_form.districts }}
</div>
</p>
<p>
<div class="b-modal__item">
<span>{{ location_form.regions.label }}</span>
{{ location_form.regions }}
</div>
</p>
<p>
<div class="b-modal__item">
<span>{{ location_form.cities.label }}</span>
{{ location_form.cities }}
</div>
</p>
<br />
<div class="b-modal__item b-modal__item_btn">
<input class="b-btn b-btn_red" type="submit" value="Сохранить">
</div>
</div>
</form>
</div>
<!-- end snippet -->
cities download form on the page where the brakes modal window!
<fieldset>
<legend>The territory of distribution of the ads</legend>
{{ form.country|add_class:"b-input__input js-select" }}
{{ form.districts|add_class:"b-input__input js-select chosen-select" }}
{{ form.regions|add_class:"b-input__input js-select chosen-select" }}
{{ form.cities|add_class:"b-input__input js-select chosen-select" }}
{# form.geo|add_class:"b-input__input" #}
</fieldset>
As you explain it, you have a lot of data to get (countries, cities), if you do it in php, you will lock the page until you retrive all those datas.
To have a shorter loading time, you just have to make everything in js (ajax).
You load your page with the cities, countries, ... without data.
Once the page is loaded (document.ready), you call your ajax to fill your cities, countries and so on.

Categories