django: adding a form to formset in template causing issues - javascript

I know this kind of question are recurrent here and I have searched around for hours for an answer but nothing this seems to solve the issue.
I have a formset where the user can dynamically add a form. The formset works well when there is only form, but when the user adds a form, this newly added form does not get saved in the database table which lead me to think that there is an issue with the adding button. My limited skills in programming and especially Javascript prevent me from going further in understanding what is going on
here is my view:
def New_Sales(request):
#context = {}
form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount'))
if request.method == 'GET':
formset = form(queryset= historical_recent_data.objects.none())
elif request.method == 'POST':
formset = form(request.POST)
if formset.is_valid():
for check_form in formset:
quantity = check_form.cleaned_data.get('Quantity')
id = check_form.cleaned_data.get('Id')
update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity)
update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity)
check_form.save()
return redirect('/dash2.html')
#else:
#form = form(queryset= historical_recent_data.objects.none())
return render(request, 'new_sale.html', {'formset':formset})
and here is the template:
<form method="POST" class="form-validate" id="form_set">
{% csrf_token %}
{{ formset.management_form }}
<table id="form_set" class="form">
{% for form in formset.forms %}
{{form.non_field_errors}}
{{form.errors}}
<table class='no_error'>
{% crispy form %}
</table>
{% endfor %}
</table>
<div id="form_set" style="display:none">
<table class='no_error'>
{% crispy formset.empty_form %}
</table>
</div>
</div>
<br>
<br>
</form>
<button class="btn btn-success" id="add_more">Add</button>
<button class="btn btn-primary" type="submit" form="form_set">Save</button>
</section>
</div>
</div>
<footer class="footer">
<div class="footer__block block no-margin-bottom">
<div class="container-fluid text-center">
<div class ="row text-center">
<div class="col-lg-3">
<form id= "form_{{ language.code }}" action="{% url 'set_language' %}" method="post">{% csrf_token %}
<input type="hidden" name="text" value="{{ redirect_to }}">
<select name="language" id="">
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}>
{{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
<button type="submit" value="Go" class="learn_more2">Go</button>
</form>
</div>
<div class="col-lg-3">
<p class="no-margin-bottom align-items-center" >2020 © Exostock.<a></a></p>
</div>
<div class="col-lg-3">
<span>Support</span>
</div>
</div>
</div>
</div>
</footer>
</div>
</div>
<!-- JavaScript files-->
<script src="{% static 'vendor/jquery/jquery.min.js' %}"></script>
<script src="{% static 'vendor/popper.js/umd/popper.min.js' %}"> </script>
<script src="{% static 'vendor/bootstrap/js/bootstrap.min.js' %}"></script>
<script src="{% static 'vendor/jquery.cookie/jquery.cookie.js' %}"> </script>
<script src="{% static 'vendor/chart.js/Chart.min.js' %}"></script>
<script src="{% static 'vendor/jquery-validation/jquery.validate.min.js' %}"></script>
<script src="{% static 'js/charts-home.js' %}"></script>
<script src="{% static 'js/front.js' %}"></script>
</body>
</html>
<script type='text/javascript'>
$('#add_more').click(function() {
var form_idx = $('#id_form-TOTAL_FORMS').val();
$('#form_set').append($('#form_set').html().replace(/__prefix__/g, form_idx));
$('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
</script>
There is no error outputed, neither on screen or in the logs, but I am sure something is wrong with the form that get created because only the original one gets into db

Related

How to use Flask-Moment with dynamically generated HTML?

I have API that generates table that uses Flask-Moment. API returns HTML code and then it's displayed on the page, but column that uses Flask-Moment is empty. I think it's somehow connected with the fact that Flask-Moment can't (probably) work with dynamically generated HTML.
So, how to use Flask-Moment with dynamically generated HTML?
Table screenshot
responses/submissions.html:
<div class="submissions_table">
<div class="table_header__wrapper">
<div class="table_header">
{# Result #}
<div class="table_header_column result">
<p>RESULT</p>
</div>
{# Language #}
<div class="table_header_column language">
<p>LANGUAGE</p>
</div>
{# Time #}
<div class="table_header_column time">
<p>TIME</p>
</div>
{# View result #}
<div class="table_header_column view_result"></div>
</div>
</div>
<div class="table_body">
{% for submission in submissions %}
<div class="table_row__wrapper">
<div class="table_row">
{# Result #}
{% set submission_result = submission.get_result() %}
{% if submission_result['success'] %}
{% set result_status = 'success' %}
{% else %}
{% set result_status = 'fail' %}
{% endif %}
<div class="table_row_column result {{ result_status }}">
{# Status icon #}
{% if submission_result['success'] %}
<i class="result__icon far fa-check-circle"></i>
{% else %}
<i class="result__icon far fa-times-circle"></i>
{% endif %}
<p>{{ submission_result['message'] }}</p>
</div>
{# Language #}
<div class="table_row_column language">
{% set language_info = languages.get_info(submission.language) %}
<img src="{{ language_info['icon'] }}" alt="" class="language__icon">
<p class="language__name">{{ language_info['fullname'] }}</p>
</div>
{# Time #}
<div class="table_row_column time">{{ moment(submission.submission_date).fromNow() }}</div>
{# View result #}
<div class="table_row_column view_result">View Result</div>
</div>
</div>
{% endfor %}
</div>
</div>

Django - Why does this TableView has two paginators?

In my Django project I have a view that has two paginators, and I can't identify where each of them comes from. They look like this:
I want to delete one of them, but I realized they are not working the same way.
The one above to the right always paginates 25 results (10 on the first, 10 on the second and 5 on the third page.
The one below seems to be dividing the whole queryset in sets of 25, which then the other paginator iterates over.
So, for example, if I have 100 rows, the paginator below says there's 4 pages. If I select the number 2 in that paginator, the paginator on the right iterates over those 25 rows, and not the whole queryset.
My view looks like this:
class ClientTableView(AdminPermissionsMixin, PagedFilteredTableView):
model = Client
table_class = ClientTable
template_name = 'users/client/client_table.html'
filter_class = ClientFilter
formhelper_class = ClientFormHelper
exclude_columns = ('actions',)
export_name = 'regiones'
def get_context_data(self, **kwargs):
context = super(ClientTableView, self).get_context_data(**kwargs)
context['allows_user_creation'] = self.request.user.users_permission == '2'
return context
def get_queryset(self, **kwargs):
qs = super(ClientTableView, self).get_queryset()
qs = qs.filter(allows_credit=False)
return qs
The template client_table.html looks like this:
{% extends "table.html" %}
{% load staticfiles %}
{% block users_active %}active{% endblock %}
{% block page_title %}Clientes{% endblock page_title %}
{% block table_title %}Lista de clientes{% endblock %}
{% block breadcrumb %}
{{ block.super }}
<li class="breadcrumb-item accordion active">Lista de clientes</li>
{% endblock %}
{% block table_actions %}
<a href="{% url "credit_client_list" %}" class="mb-sm btn btn-primary" style="margin-right: 10px">Clientes
cartera</a>
{% if allows_user_creation %}
<i class="fa fa-plus-square"></i>Agregar cliente
{% endif %}
{{ block.super }}
{% endblock %}
{% block js %}
<script src="{% static "js/table-spanish.js" %}"></script>
{% endblock %}
And table.html looks like this:
{% extends "base.html" %}
{% load django_tables2 crispy_forms_tags staticfiles %}
{% block content %}
<div class="card card-custom gutter-b">
<div class="card-header flex-wrap py-3">
<div class="card-title">
<h3 class="card-label">
<i class="fas {% block table_icon %}fa-list-alt{% endblock %}"></i>
{% block table_title %}{% endblock %}
</h3>
</div>
<div class="card-toolbar">
{% block table_actions %}
{% if object_list|length > 0 %}
<div class="dropdown dropdown-inline ml-2">
<button type="button" class="btn btn-light-primary font-weight-bolder dropdown-toggle"
data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fas fa-file-export"></i>Exportar
</button>
<!--begin::Dropdown Menu-->
<div class="dropdown-menu dropdown-menu-sm dropdown-menu-right" style="">
<!--begin::Navigation-->
<ul class="navi flex-column navi-hover py-2">
<li class="navi-header font-weight-bolder text-uppercase font-size-sm text-primary pb-2">
Elige una opción:
</li>
<li class="navi-item">
<a href="{% url 'export_pdf' "local" %}" class="navi-link">
<span class="navi-icon">
<i class="far fa-file-pdf"></i>
</span>
<span class="navi-text">PDF</span>
</a>
</li>
<li class="navi-item">
<a href="{% url 'export_xlsx' "local" %}" class="navi-link">
<span class="navi-icon">
<i class="far fa-file-excel"></i>
</span>
<span class="navi-text">XLSX</span>
</a>
</li>
</ul>
<!--end::Navigation-->
</div>
<!--end::Dropdown Menu-->
</div>
{% endif %}
{% endblock %}
</div>
</div>
<div style="display: inline-block">
{% block table_statistics %}{% endblock %}
</div>
<div class="card-body">
{% block body_table %}
<div class="row">
<div class="col-sm-12 col-md-12 mb-5">
<div id="datatable1_filter" class="dataTables_length">
{% crispy filter.form %}
{# <label>Buscar:<input type="search" class="form-control form-control-sm" placeholder="" aria-controls="DataTables_Table_0"></label>#}
</div>
</div>
</div>
<form action="{% block url_table_actions %}{% endblock %}" method="post" id="action">
{% csrf_token %}
{% block table %}
{% render_table table "django_tables2/bootstrap4.html" %}
{% endblock %}
<input type="hidden" name="command" id="command"/>
</form>
{% endblock %}
{% block table_bottom %}
{% endblock table_bottom %}
</div>
</div>
{% endblock %}
{% block js %}
{# <script src="{% static "js/datatables.bundle.js" %}"></script>#}
<script src="{% static "js/basic.js" %}"></script>
{% endblock %}
WHAT I KNOW
I identified that the paginator on the right, is added by the line <script src="{% static "js/table-spanish.js" %}"></script> in client_table.html, and if I remove that line, that paginator disappears, and the other one iterates correctly over the whole queryset.
However, I would really like to keep that line, since it also gives me other functionalities which I'd rather keep simple.
I'd like to identify what line or library could be responsible for the other paginator, the one below and, if possible, delete that one instead and let the paginator on the right iterate over the whole queryset.
I think you're right side pagination is datatables.js and the lower pagination is from Django-tables2. Django-tables2 is going to give you pagination for that by default, you can easily disable it.
https://django-tables2.readthedocs.io/en/latest/pages/pagination.html#disabling-pagination
Just add table_pagination = False
class ClientTableView(AdminPermissionsMixin, PagedFilteredTableView):
table_pagination = False
(django-filters' PagedFilteredTableView inherits from django-tables2' SingleTableView)

Custom popup message rendering but button not working?

I have a custom popup that shows upon form submission to let the user know it was successful. Currently it displays when it's supposed to (although I can't get it to display in the middle right on top, but that's a minor issue) like shown below:
But the little X button does not actually close the message. You can click it but it does nothing, and if you reload the page then it's gone until you submit again.
base.html
{% load static purchasing_tags humanize %}
{% include 'operations/message.html' %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="{% static 'images/favicon.ico' %}" type="image/x-icon" rel="shortcut icon"/>
<link href="https://fonts.googleapis.com/css?family=Lato:300,400,700" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="{% static "css/plugins/bootstrap.min.css" %}" rel="stylesheet">
<link href="{% static "css/apps.css" %}" rel="stylesheet">
<script src="{% static "js/plugins/jquery.js" %}"></script>
<script src="{% static "js/plugins/bootstrap.min.js" %}"></script>
<!--[if lt IE 9]>
<script src="{% static 'js/plugins/respond.js' %}"></script>
<![endif]-->
</head>
<body>
<div id="login" class="panel panel-default">
<div class="panel-body">
{% block main %}
{% endblock main %}
</div>
<div class="panel-footer">
{% block panel_footer %}
{% endblock %}
</div>
</div>
{% if messages %}
<script>
{% for message in messages %}
$(document).ready(function () {
$('.toast').toast('show');
});
{% endfor %}
</script>
{% endif %}
</body>
I think the problem could be related to the warning I get that says Unresolved function or method toast() on $('.toast').toast('show'); but I'm not sure how to resolve this issue (I got this from https://www.w3schools.com/bootstrap4/bootstrap_toast.asp but I don't know if I just didn't add something important to make this work)
enter_exit_area.html
{% extends "base.html" %}
{% load core_tags %}
{% block main %}
<form id="warehouseForm" action="" method="POST" class="form-horizontal" novalidate >
{% csrf_token %}
<div>
<div>
<label>Employee</label>
{{ form.employee_number }}
</div>
<div>
<label>Work Area</label>
{{ form.work_area }}
</div>
<div>
<label>Station</label>
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter" >Enter Area</button>
</div>
</div>
</form>
{% endblock main %}
message.html
{% for message in messages %}
<div style="position: absolute" class="bg-{% if message.tags == 'error' %}danger{% else %}{{message.tags}}{% endif %}" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000">
<div>
<strong class="mr-auto">
{{message.tags|capfirst}}
</strong>
<button type="button" class="ml-2 mb-1 close" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div>
{{message|safe}}
</div>
</div>
{% endfor %}
views.py
class EnterExitArea(CreateView):
model = EmployeeWorkAreaLog
template_name = "operations/enter_exit_area.html"
form_class = WarehouseForm
def form_valid(self, form):
emp_num = form.cleaned_data['employee_number']
area = form.cleaned_data['work_area']
station = form.cleaned_data['station_number']
if 'enter_area' in self.request.POST:
form.save()
EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True)).update(time_in=datetime.now())
messages.success(self.request, "You have entered")
return HttpResponseRedirect(self.request.path_info)
The close button is missing the attribute data-dismiss="toast"
You'd need to add the toast class to the containing div though as well
https://www.w3schools.com/bootstrap4/bootstrap_toast.asp

jQuery's fadeToggle() selects more elements than desired

$(document).ready(function(event) {
$(".reply-btn").click(function() {
$(".section-row-reply").closest(".section-row-reply").fadeToggle();
});
});
I have a for-loop that generates the following:
comments
replies
reply form.
I want the jquery function,fadeToggle() to reveal the reply form for each comment when the reply button is clicked
<!-- jquery 2.2.4 -->
<script src="{% static 'js/jquery.min.js' %}"></script>
<!-- bootstrap 3.3.7 -->
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script src="{% static 'js/jquery.stellar.min.js' %}"></script>
<script src="{% static 'js/main.js' %}"></script>
<!-- post comments -->
<div class="section-row">
<div class="section-title">
<h3 class="title">{{ comments.count }} Comment{{ comments|pluralize }}</h3>
</div>
<div class="post-comments">
{% for comment in comments %}
{% if comment %}
<!-- comment -->
<div class="media">
<div class="media-left">
<img class="media-object" src="{{ comment.profile_picture.url }}" alt="">
</div>
<div class="media-body">
<div class="media-heading">
<h4>{{ comment.user }}</h4>
<span class="time">{{ comment.timestamp }}</span>
</div>
<p>{{ comment.content }}</p>
<div class="rely-button">
<button type="button" name="button" class="reply-btn btn btn-outline-dark btn-sm" id="reply-button">Reply</button>
</div>
<br>
<!-- display replies to the comment -->
{# reply per comment #}
{# all replies to comments will be shown below the comment #}
{% if comment.replies %}
{% for reply in comment.replies.all %}
<div class="media-replies pull-right">
<div class="media-left">
<img class="media-object" src="{{ reply.profile_picture.url }}" alt="">
</div>
<div class="media-body">
<div class="media-heading">
<h4>{{ reply.user }}</h4>
<span class="time">{{ reply.timestamp }}</span>
</div>
<p>{{ reply.content }}</p>
</div>
</div>
{% endfor %} {# endfor comment.replies #}
{% endif %} {# endif comment.replies #}
<!-- /display replies to parent comment -->
{# after replies have been shown, we can have the reply-comment-form #}
{% if user.is_authenticated %}
<!-- post reply -->
<div class="section-row-reply pull-right" style="display:none" id="show-reply-form">
<form class="post-reply" method="post">
{% csrf_token %}
<input type="hidden" name="comment_id" value="{{ comment.id }}">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<textarea class="input" name="content" placeholder="Reply here..."></textarea>
</div>
</div>
<div class="col-md-12">
<button class="primary-button" value="submit" type="submit">Reply</button>
</div>
<!-- form_errors -->
{{ comment_form.errors }}
</div>
</form>
</div>
<!-- /post reply -->
{% endif %} {# endif user.is_authenticated #}
{# comments are display in the manner above in the div section #}
</div>
</div>
{% endif %} {# endif comment #}
{% endfor %} {# endfor comment in comments #}
</div>
</div>
<!-- /post comments -->
This is a django powered site hence the {% %}, {# #} and {{ }} at the html layer. The function works but not exactly. When any reply button is clicked (to display the reply form), other reply forms for other comments are displayed.
**The idea is to make the reply button for each comment display only the reply form for that comment. Any help will be greatly appreciated. I suspect my selection of elements at the jquery layer. **
all css are that of bootstrap 3.3.7

Include template with dynamic Django form

I have a model with a choices field, and the creation form has different fields depending on the field. I'm implementing the design of a dashboard in which the user can click a button (one button for each choice) and a model containing the model form will be displayed.
I want to use a template only for the model and send the form and action URL to it depending on which button the user clicks, but that would mean I have to mix JS and Django variables and I don't know if that's a good idea.
The code right now is something like this:
dashboard.html
<div class="add-connections">
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if user_connections.EP %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if user_connections.OLX %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if user_connections.CC %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if user_connections.FR %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
</div>
{% url 'create_olx_connection' as olx_url %}
{% url 'create_ep_connection' as ep_url %}
{% url 'create_cc_connection' as cc_url %}
{% url 'create_fr_connection' as fr_url %}
{% include "properties/dashboard/connection_modal.html" %}
connection_modal.html
<!-- Modal -->
<div class="modal fade modal-property" id="modal-new-connection" tabindex="-1" role="dialog" aria-labelledby="myConnectionModal">
<div class="modal-dialog" role="document">
<div class="modal-content panel-success">
<div class="modal-header panel-heading">
<button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title text-uppercase text-white"><b>Connections</b></h4>
</div>
<div class="modal-body">
<form action="{{ action_url }}"
{{ form.as_p }}
<div>
<button type="submit" class="btn btn-outline-success">Activate connection</button>
Cancel
</div>
</form>
</div>
</div>
</div>
</div>
views.py
def get_context_data(self, **kwargs):
context = super(
ManageServicesView, self).get_context_data(**kwargs)
...
context['connection_forms'] = {
'olx_form': OLXform(),
'el_pais_form': ElPaisForm(),
'finca_raiz_form': FincaRaizForm(),
'calicasa_form': CaliCasaForm()
}
return context
I want something like {% include "properties/dashboard/connection_modal.html" with form=chosen_form and action_url=chosen_url %} but I don't know how to link each button's click event with Django variables to be able to do that. I don't want to code a model for each option, I think it has to be a cleaner way. I'd appreciate your suggestions.
You could put a {% for ... %} loop in connection_modal.html to generate all the modals, with the correct forms, that you need. Than put a another for loop in dashboard.html to create the correct links.
Tweaking views.py:
context['connections'] = {
'OLX': {
'form' : OLXform(),
'user_connected': user_connections.OLX
},
'EP': {
'form' : ElPaisForm(),
'user_connected': user_connections.EP
},
# other connections here
}
dashboard.html:
{% for connection,data in user_connected.items %}
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if data.user_connected %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
{% endfor %}
connection_modal.html:
{% for connection,data in user_connected.items %}
{% if not data.connected %}
<!-- Modal for {{connection}} -->
<div id="modal-new-connection-{{connection}}" class="modal fade modal-property" tabindex="-1" role="dialog" aria-labelledby="myConnectionModal">
<!-- modal code before form -->
{{ data.form }}
<!-- modal code after form -->
</div>
{% endif %}
{% endfor %}
This should create as many modals as you need, each with their own id value, that can be called from the appropriate link. For example modal id "modal-new-connection-OLX" will be created with the OLX form and be called from the OLX link.

Categories

Resources