Reload the page after clicking a form button in IE - javascript

I have a problem with my web site.
I have a button that displays the form and the problem is that on IE and on the edge when I click this button it shows me the form but refreshed the page automatically after the click.
I do not know how to solve this problem. Can you help me please ?
Here is my code html :
<div class="col-xs-3" id="div6">
<div style="text-align: center; color: #333; font-weight:bold;">Actualité</div>
{% if user.is_authenticated %}
{% if request.user.is_staff %}
<form action="#modification">
<div style="text-align: center;">
<button type="submit" id="modifier" class="btn btn-primary">Modifier l'actu</button>
</div>
</form>
<form action="#modification" id="formActu" style="display: none" method="post">
{% csrf_token %}
<div id="modification"></div>
<div style="text-align: center;">
<button type="submit" class="btn btn-success" id="valider" style="margin-top: 1%;">Valider</button>
</div>
</form>
{% endif %}
{% endif %}
{% if not actu %}
<div id="messageNonActu" style="margin-top: 5%;">Pas d'actualité pour le moment !</div>
{% endif %}
{% for actuCommentaire in actu %}
<div id="commentaireActu" style="margin-top: 5%;">{{actuCommentaire.commentaire}}</div>
{% endfor %}
</div>
Here is my script :
$(document).ready(function(){
var compteur = 0;
$('#modifier').click(function(){
if(compteur === 0){
$('#modification').append('{% for field in form %}<label class="my_class" for="{{ field.name|escapejs }}">{{ field.label|escapejs }} :</label>{{ field|escapejs }}{% endfor %}');
$('#formActu').show()
$('#exampleTextarea').css({resize: 'none'});
$('#commentaireActu').hide();
$('#messageNonActu').hide();
$('#modifier').removeClass('btn btn-primary').addClass('btn btn-danger');
$('#modifier').html("Annuler la modif");
compteur++;
}else{
if($('#formActu').is(':visible')){
$('#formActu').hide();
$('#commentaireActu').show();
$('#modifier').removeClass('btn btn-danger').addClass('btn btn-primary');
$('#modifier').html("Modifier l'actu");
}else{
$('#commentaireActu').hide();
$('#formActu').show();
$('#modifier').removeClass('btn btn-primary').addClass('btn btn-danger');
$('#modifier').html("Annuler la modif");
}
}
});
});
Image 1 with just button
After clicking I have a preview of the second image but it refreshed the page in less than a second after clicking on the button
Image 2 with form
Then I get the visual of the first image directly

Try this and check:(Just return false from the end of method because IE considers button click as submit that's why your page reloads)
$('#modifier').click(function(){
//your logic
return false;
}

Related

Converting inline javascript to Alpine.js

I'm trying to avoid inline javascript and would like to convert it to Alpine.js code. Is there a way to rewrite the following piece of code in Alpine.js?
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function () {
const message = "Do you really want to remove the selected e-mail address?";
const actions = document.getElementsByName('action_remove');
if (actions.length) {
actions[0].addEventListener("click", function (e) {
if (!confirm(message)) {
e.preventDefault();
}
});
}
});
document.addEventListener('DOMContentLoaded', function () {
$('.form-group').removeClass('row');
})
</script>
Here is the full context (I'm working with Django templates):
{% extends "account/base.html" %}
{% load tailwind_filters %}
{% load crispy_forms_tags %}
{% block head_title %}
Account
{% endblock %}
{% block inner %}
<h1>E-mail Addresses</h1>
{% if user.emailaddress_set.all %}
<p>The following e-mail addresses are associated with your account:</p>
<form action="{% url 'account_email' %}" class="email_list" method="post">
{% csrf_token %}
<fieldset class="blockLabels">
{% for emailaddress in user.emailaddress_set.all %}
<div class="radio">
<label for="email_radio_{{forloop.counter}}" class="{% if emailaddress.primary %}primary_email{%endif%}">
<input id="email_radio_{{forloop.counter}}" type="radio" name="email" {% if emailaddress.primary or user.emailaddress_set.count == 1 %}checked="checked" {%endif %} value="{{emailaddress.email}}" />
{{ emailaddress.email }}
{% if emailaddress.verified %}
<span class="verified">Verified</span>
{% else %}
<span class="unverified">Unverified</span>
{% endif %}
{% if emailaddress.primary %}<span class="primary">Primary</span>
{% endif %}
</label>
</div>
{% endfor %}
<div class="form-group">
<button class="secondaryAction btn btn-primary" type="submit" name="action_primary">Make Primary</button>
<button class="secondaryAction btn btn-primary" type="submit" name="action_send">Re-send Verification</button>
<button class="primaryAction btn btn-primary" type="submit" name="action_remove">Remove</button>
</div>
</fieldset>
</form>
{% else %}
<p><strong>Sad news:</strong>You currently do not have any e-mail address set up. You should add an e-mail address so you can receive notifications, reset your password, etc.</p>
{% endif %}
<h2>Add E-mail Address</h2>
<form method="post" action="{% url 'account_email' %}" class="add_email">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-primary" name="action_add" type="submit">
Add E-mail
</button>
</form>
{% endblock %}
{% block inline_javascript %}
{{ block.super }}
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function () {
const message = "Do you really want to remove the selected e-mail address?";
const actions = document.getElementsByName('action_remove');
if (actions.length) {
actions[0].addEventListener("click", function (e) {
if (!confirm(message)) {
e.preventDefault();
}
});
}
});
document.addEventListener('DOMContentLoaded', function () {
$('.form-group').removeClass('row');
})
</script>
{% endblock %}
You can try something like this:
Initialize the parent form element with x-data and set the state variable confirmMsg to null.
On form submit you prevent the actual submit with #submit.prevent and check whether a confirm message (confirmMsg) was set. If yes, you prompt the user to confirm the set message. If the users confirms, you reset the confirmMsg to null and submit the form with $el.submit().
On the buttons, you can just set the respective confirmMsg with #click = "confirmMsg = 'Are you sure?'".
Here is a code example:
<script src="//unpkg.com/alpinejs" defer></script>
<form
x-data="{confirmMsg: null}"
#submit.prevent="
if (confirmMsg && !confirm(confirmMsg)) return;
confirmMsg = null;
alert('Submitting form...'); $el.submit()"
>
<button
#click="confirmMsg = 'Do you really want to remove the selected e-mail address?'"
type="submit"
name="action_remove"
>
Remove
</button>
</form>

Django and Ajax. js not running

I hope anyone can help me with my code. I have here this html that was a js function with the goal that, whenever someone changes the "filament" option, it will change the "colors" available options available in the select:
<form method="post" enctype="multipart/form-data" style="max-width: 1000px;">
{% csrf_token %}
{{ form.as_p }}
{% for message in messages %}
<div class="alert alert-success">
<a class="close" href="#" data-dismiss="alert">×</a>
{{ message }}
</div>
{% endfor %}
<h2 class="sr-only">Login Form</h2>
<div class="illustration">
<div class="form-group">
<input type="file" name="printingfile"/ style="font-size: medium;">
<select class="form-select" aria-label="Default select example" id="=filament">
<option value="1">PLA</option>
<option value="2">ABS</option></select>
<select class="form-select" aria-label="Default select example" id="=color"></select>
<button class="btn btn-primary btn-block" type="submit">Submit</button></div>
</div>
</form>
</section>
<div></div>
<script src="{% static 'assets/js/jquery.min.js'%}"></script>
<script src="{% static 'assets/bootstrap/js/bootstrap.min.js'%}"></script>
<script src="{% static 'assets/js/Animated-Text-Background.js'%}"></script>
<script src="{% static 'assets/js/Cookie-bar-footer-popup.js'%}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
{% block javascript %}
<script> //updating the colors available
$("#filament").change(function () {
var filament = $(this).val();
var color = $('#color');
console.log(filament);
$.ajax({
url: '/get_colors/',
data: {
'filament': filament
},
dataType: 'json',
success: function (data) {
color.empty();
for (var i = 0; i < data.lenght; i++) {
color.append('<option value=' + data[i].name + '>' + data[i].name + '</option>');
}
}
});
});
</script>
{% endblock javascript %}
</body>
</html>
This calls a view in Django. I know that the problem is here because I tried to use console.log and got 0 results, so probably there is nothing wrong (for now) in the Python code. Anyone could help me? Stuck here for hours and any tip would be really helpfull!

How to handle JavaScript event inside a inlineformset_factory with formset_media_js

I have an inlineformset_factory implemented with formset_media_js, these two by itself are working ok. What I need to implement is to be able to handle the enable and disable state of some checkboxes and input fields that are inside the inlineformset_factory.
I have a javascript that works on the first group of formset created on page load, but when a new formset is added by the user the javascript is not working.
How can I handle the new formsets input fields added by the user with javascript?
If "is chapter" is checked then "is subchapter" and "quantity" are disabled, by default the inlineformset_fatory creates 1 formset on page load, on this formset the javascript works. But when the user adds another formset with button "Add another Budget Item" the javascript is no longer working. If for example, I configure the inlineformser_factory to create 3 formset on page load the javascript works on those 3 formset but not on the formsets added by the user.
forms.py : at this forms.py i have the inlineformset_factory that is created every time the user adds a formset.
from django import forms
from django.forms import inlineformset_factory
from djangoformsetjs.utils import formset_media_js
from accounts.models import ProjectManager
from projects.models import Project, BudgetModel, BudgetModelItems
class CreateBudgetItem(forms.ModelForm):
class Media(object):
js = formset_media_js
class Meta:
model = BudgetModelItems
fields = ('budget_model',)
widgets = {
'budget_item_description': forms.Textarea(attrs={'rows': 2, 'cols': 50}),
'budget_item_item': forms.NumberInput(attrs={'size': 6}),
'budget_item_quantity': forms.NumberInput(attrs={'size': 6}),
}
BudgetItemFormset = inlineformset_factory(BudgetModel, BudgetModelItems,
form=CreateBudgetItem,
fields=('budget_model', 'budget_item_item',
'budget_item_description', 'budget_item_unit',
'budget_item_quantity', 'budget_item_is_chapter',
'budget_item_is_subchapter'),
extra=1,
can_delete=True,
can_order=True
)
views.py
from django.shortcuts import render, redirect
from django.forms import formset_factory
from accounts.models import ProjectManager
from projects.forms.create_project import CreateProjectForm
from projects.forms.create_budgetmodel import BudgetFormset, ProjectForBudgetModel
from projects.forms.create_budgetitem import CreateBudgetItem, BudgetItemFormset
from projects.models import BudgetModel, Project
def create_budget_item(request):
user = request.user.projectmanager
projects = Project.objects.filter(project_manager_id=user)
models = BudgetModel.objects.none()
project_form = ProjectForBudgetModel(user)
budget_item_form = CreateBudgetItem()
formset = BudgetItemFormset()
for project in projects:
models |= BudgetModel.objects.filter(project_id=project.pk)
budget_item_form.fields['budget_model'].queryset = models
if request.method == 'POST':
project_form = ProjectForBudgetModel(user, request.POST)
budget_item_form = CreateBudgetItem(request.POST)
if project_form.is_valid() and budget_item_form.is_valid():
# project_id = project_form.cleaned_data['project']
budget_model_id = budget_item_form.cleaned_data['budget_model']
formset = BudgetItemFormset(request.POST, instance=budget_model_id)
if formset.is_valid():
formset.save()
context = {'project_form': project_form,
'bi_form': budget_item_form,
'formset': formset,
'models': models}
return render(request, 'projects/create_budget_items.html', context)
budget_item_form.html: this form is called (included) at create_budget_items.html
<div data-formset-form>
<div class="card">
<div class="card-body">
<div class="row">
<div class="col">
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col">Item</th>
<th scope="col">Description</th>
<th scope="col">Unit</th>
<th scope="col">Quantity</th>
<th scope="col">Is Chapter</th>
<th scope="col">Is SubChapter</th>
</tr>
</thead>
<tbody>
<tr>
<th>{{ form.budget_item_item }}</th>
<td>{{ form.budget_item_description }}</td>
<td>{{ form.budget_item_unit }}</td>
<td>{{ form.budget_item_quantity }}</td>
<td>{{ form.budget_item_is_chapter }}</td>
<td>{{ form.budget_item_is_subchapter }}</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-auto">
{% if form.ORDER %}
<div class="row mt-1">
<div class="d-none">{{ form.ORDER }}</div>
<button class="btn btn-info btn-block" type="button" data-formset-move-up-button>
{% trans 'Move up' %}
</button>
</div>
<div class="row mt-1">
<button class="btn btn-info btn-block" type="button" data-formset-move-down-button>
{% trans 'Move down' %}
</button>
</div>
{% endif %}
</div>
<div class="col col-lg-2 mt-1">
{% if form.DELETE %}
<div class="d-none">{{ form.DELETE }}</div>
<button type="button" class="btn btn-danger btn-block h-100" data-formset-delete-button>
{% trans 'Delete' %}
</button>
{% endif %}
</div>
</div>
</div>
</div>
</div>
create_budget_items.html: On this template I have the javascript where I control the enable and disable states of checkboxes and input fields. I thought that by calling the script inside the for loop where the formset is being iterated I was going to be able to control the input fields of the formsets added by the user. Is only working on the formsets created on page load.
{% block dashboard_head %}
{{ formset.media }}
<script type="text/javascript">
function trackDisabled(trigger_id, ...targets) {
const checkbox = document.getElementById(trigger_id);
checkbox.addEventListener('change', e => {
console.log(e.target.checked);
{#console.log(trigger_id);#}
{#console.log(...targets);#}
if (e.target.checked === true) {
targets.forEach(x => {
const element = document.getElementById(x);
element.disabled = true;
element.checked = false;
element.value = ''
})
} else {
targets.forEach(x => document.getElementById(x).disabled = false)
}
})
}
</script>
{% endblock dashboard_head %}
{% block dashboard_content %}
<h1>Create Budget Items</h1>
<form method="post">
{% csrf_token %}
{{ project_form.project }}
<select name="budget_model" id="id_budget_model" class="form-control">
{% with value=bi_form.budget_model.value %}
{% for model in models %}
<option value="{{ model.pk }}" class="{{ model.project.pk }}"
{% if model.pk|slugify == value|slugify %}selected="selected"{% endif %}>
{{ model.budget_name }}
</option>
{% endfor %}
{% endwith %}
</select>
{% load formset_tags %}
<div id="formset" data-formset-prefix="{{ formset.prefix }}">
{{ formset.management_form }}
<div data-formset-body>
{% for form in formset %}
{% include "projects/budget_item_form.html" with form=form only %}
<script>
trackDisabled(
'{{ form.budget_item_is_chapter.auto_id }}',
'{{ form.budget_item_is_subchapter.auto_id }}',
'{{ form.budget_item_quantity.auto_id }}'
);
console.log('{{ form.budget_item_is_chapter.auto_id }}');
</script>
{{ form.errors }}
{% endfor %}
</div>
<script type="form-template" data-formset-empty-form>
{% escapescript %}
{% include "projects/budget_item_form.html" with form=formset.empty_form only %}
{% endescapescript %}
</script>
<div class="row mt-3 mr-1 ml-1">
<!-- This button will add a new form when clicked -->
<div class="col text-center">
<input class="w-75 btn btn-info" type="button"
value="{% trans 'Add another Budget Item' %}" data-formset-add>
</div>
<div class="col text-center">
<button class="w-75 btn btn-success" type="submit">
{% trans 'Create Models' %}
</button>
</div>
</div>
</div>
</form>
{% endblock dashboard_content %}
This is the javascript that finally worked out, was written by a friend.. Thank you FunkyBob!
<script>
function isChapter() {
const root = document.getElementById('formset');
const prefix = root.dataset.formsetPrefix;
console.log({root, prefix});
// listen for all input changes
root.addEventListener('change', ev => {
// check if it matches out name pattern
console.log(ev.target.name);
console.log(ev.target.checked, !ev.target.checked);
console.log(`${prefix}-(\\d+)-budget_item_is_chapter`);
let m = ev.target.name.match(RegExp(`${prefix}-(\\d+)-budget_item_is_chapter`));
// if it's not {prefix}-*-budget_item_is_chapter ignore
if (!m) return;
console.log(m);
let idx = m[1]; // the matched regex group
// Find the related fields, and set them as enabled/disabled
root.querySelector(`[name="${prefix}-${idx}-budget_item_is_subchapter"]`).disabled = ev.target.checked;
root.querySelector(`[name="${prefix}-${idx}-budget_item_is_subchapter"]`).checked = false;
root.querySelector(`[name="${prefix}-${idx}-budget_item_unit"]`).disabled = ev.target.checked;
root.querySelector(`[name="${prefix}-${idx}-budget_item_unit"]`).value = ev.target.checked;
root.querySelector(`[name="${prefix}-${idx}-budget_item_quantity"]`).disabled = ev.target.checked;
root.querySelector(`[name="${prefix}-${idx}-budget_item_quantity"]`).value = ev.target.checked;
console.log("Done!")
});
}
isChapter();
</script>

Using Select2 with flask-wtforms

After select2 manipulates the dropdown field the regular use of form.owner_id.data yields None. How can I extract the selected option from a select2 field.
If I disable the select2 javascript, wtforms will work just fine and I will be able to use form.owner_id.data. (but it looks ugly)
screenshot of rendered form
forms.py
class ProjectForm(FlaskForm):
owner_id = SelectField('Owner:', [validators.Required()], choices=[], render_kw={"placeholder": "Owner company *"})
(rest of form has been truncated for simplicity)
views.py
#app.route('/new_project/<int:company_id>', methods=('GET', 'POST'))
def new_project(company_id):
membership = Membership.query.filter_by(user_id=current_user.id, company_id=company_id).first()
company = Company.query.filter_by(id=company_id).first_or_404()
form = ProjectForm()
form.owner_id.choices = [(str(comp.id), repr(comp)) for comp in Company.query.all()]
form.client_id.choices = [(str(comp.id), repr(comp)) for comp in Company.query.all()]
form.contractor_id.choices = [(str(comp.id), repr(comp)) for comp in Company.query.all()]
form.membership_id.choices = [(str(comp.id), repr(comp)) for comp in Company.query.all()]
if request.method == 'POST':
flash(str(form.owner_id.data), 'success')
if form.validate_on_submit():
project = Project()
connection = Assignment()
# PROJECT DETAILS
project.title = form.title.data
project.description = form.description.data
project.owner_id = int(form.owner_id.data)
_macro
{% macro render_select_field(field, placeholder='Select...', label='Select an option below') %}
<div class="form-group">
<label>{{ label }}</label>
<select data-placeholder="{{ placeholder }}" class="select-size-xs">
<option></option>
{% for choice in field.choices %}
<option value="{{ choice[0] }}">{{ choice[1] }}</option>
{% endfor %}
</select>
{% if field.errors %}
{% for error in field.errors %}
<span class="help-block text-danger"><i class="icon-cancel-circle2 position-left"></i>{{ error }}</span>
{% endfor %}
{% endif %}
</div>
{% endmacro %}
html
<form method="POST" action="{{ url_for('new_project', company_id=company.id) }}" enctype="multipart/form-data" role="form">
<div class="panel panel-body login-form">
<div class="text-center">
<div class="icon-object text-muted"><i class="icon-plus2"></i></div>
</div>
{{ form.hidden_tag() }}
<div class="text-center form-group"><span>Project details</span></div>
{{ new_render_field(form.title, icon="icon-quill2", class_='form-control') }}
{{ new_render_field(form.description, icon="icon-stack-text", class_='form-control', rows=10) }}
{{ render_select_field(form.owner_id, placeholder="Who's doing the work?", label="Select the owner company") }}
{{ render_select_field(form.client_id, placeholder="Where do the bills go?", label="Select the client company") }}
{{ new_render_field(form.default_client_rate, icon="icon-price-tag", class_='form-control') }}
{{ new_render_field(form.default_contractor_rate, icon="icon-price-tag", class_='form-control') }}
<!-- THE REST OF FORM HAS BEEN TRUNCATED FOR SIMPLICITY -->
<div class="form-group">
<button type="submit" class="btn bg-pink-400 btn-block">Create</button>
</div>
</div>
</form>
So after analyzing the select field in the inspect window, it became apparent that the select field is missing the name="{{ field.name }}" that wtforms requires in order to validate the form. The simple change made in my _macro was from this:
<select data-placeholder="{{ placeholder }}" class="select-size-xs">
To this:
<select data-placeholder="{{ placeholder }}" class="select-size-xs" name="{{ field.name }}">
With this addition wtforms can now validate, and find the selected option returning the proper id for form.owner_id.data.

How to load Divs in Django separately from same or different views?

I have a three pane view where the right pane loads data depending what you click on in center pane.
Right now I just have one view that returns data for all three panes (Nonefor right pane, if nothing selected in center pane pane, like when the page is first loaded)
But the problem now is, since every time something on center pane is click on, the page reloads. So all the scroll bars return to top position.
Is there a way to separately load the two panes (HTML divs) on the same page using the same or different views?
TEMPLATE:
{% block content %}
{% load guardian_tags %}
{% get_obj_perms request.user for issuelist as "issuelist_perms" %}
<section>
<div>
<strong>Currently viewing: </strong><em>{{issuelist.name}}</em>
</div>
</section>
<section><div id="basepanel" class="auto-style5">
<div id="panel1" class="auto-style5">
{% render_table issue_table "django_tables2/issue_table.html"%}
{% if "change_issuelist" in issuelist_perms %}
<form action="{% url 'srt.views.newissue' issuelist.id %}" method="get" class="add_issue">
<button type="submit" class="btn btn-default">Add Issue</button>
</form>
{% endif %}
</div>
{% if issue.id %}
<div id="panel2" class="auto-style5">
{% if "change_issuelist" in issuelist_perms %}
<form action="{% url 'srt.views.editissue' issuelist.id issue.id %}" method="get" class="add_issue">
<button type="submit" class="btn btn-default">Edit Issue</button>
</form>
{% endif %}
<strong>Title:</strong> <em>{{issue.title}}<br><br></em>
{% if "delete_issuelist" in issuelist_perms %}
<form action="{% url 'srt.views.deleteissue' issuelist.id issue.id %}" method="post" class="add_issue" onsubmit="return confirm('Do you really want to delete Issue with title: {{issue.title}}?');">{% csrf_token %}
<button type="submit" class="btn btn-default">Delete Issue</button>
</form>
{% endif %}
<strong>Summary: </strong><em>{{issue.summary}}<br><br></em>
<strong>SSS Tracking Number:</strong><span style="padding-left:1.2em;">{{issue.sss_tracking}}</span><br><br>
<strong>Cust. Tracking Number:</strong><span style="padding-left:0.2em">{{issue.customer_tracking}}</span><br>
<strong><br>Suspected Component: </strong>{{issue.suspected_component}}<br><br>
<strong>Status: </strong>{% inplace_edit "issue.status" %}<br><br>
<strong>Completed Actions/Updates:<br></strong>
{% render_table update_action_table "django_tables2/action_table.html"%}
<br><strong>Next Steps/Action:</strong>
{% if "change_issuelist" in issuelist_perms %}
<form action="{% url 'srt.views.newaction' issuelist.id issue.id %}" method="get" class="add_new_action">
<button type="submit" class="btn btn-default">Add New Action</button>
</form>
{% endif %}
{% render_table planned_action_table "django_tables2/action_table.html"%}
<br><strong>Historic Actions/Updates:<br></strong>
{% render_table historic_action_table "django_tables2/action_table.html"%}
</div>
{% if action.id %}
<div id="panel3" class="auto-style4">
<form action="{% url 'srt.views.action_attachments' issuelist.id issue.id action.id %}" method="get" class="add_issue">
<button type="submit" class="btn btn-default">Attachments</button>
</form>
<strong>Action: </strong><em>{{ action.title }}</em><br><br>
<strong>Description: </strong><em>{{ action.description }}</em><br><br>
<strong>Current Action State: </strong>{% inplace_edit "action.state" %}<br>
<!-- <strong>Issue: </strong><em>{{issue.title}}</em><br><br> -->
{% if "delete_issuelist" in issuelist_perms %}
<br>
<form action="{% url 'srt.views.deleteaction' issuelist.id issue.id action.id %}" method="post" class="add_issue" onsubmit="return confirm('Do you really want to delete the Action with title: {{action.title}}?');">{% csrf_token %}
<button type="submit" class="btn btn-default">Delete Action</button>
</form>
{% endif %}
{% if "delete_issuelist" in issuelist_perms %}
<form action="{% url 'srt.views.editaction' issuelist.id issue.id action.id %}" method="get" class="add_new_action">
<button type="submit" class="btn btn-default">Edit Action</button>
</form>
<br>
{% endif %}
<br>
{% render_table actionlog_table "django_tables2/action_table.html"%}
{% if "change_issuelist" in issuelist_perms %}
<form action="{% url 'srt.views.newactionlog' issuelist.id issue.id action.id %}" method="get" class="add_action_log">
<button type="submit" class="btn btn-default">Add Action Log</button>
</form>
{% endif %}
</div>
{% endif %}
{% endif %}
</div></section>
{% endblock %}
View for that template:
def view_issues(request, issuelist_id, issue_id=None, action_id=None):
issuelist = get_object_or_404(IssueList, id=issuelist_id)
issue_table = IssueTable(Issue.objects.filter(issuelist = issuelist).order_by("-added"), prefix="i")
if (issue_id is None) and (action_id is None):
issue = []
action = []
completed_action_list = []
planned_action_list = []
historic_action_list = []
actionlog_list = []
elif (issue_id is not None) and (action_id is None):
issue = get_object_or_404(Issue, id=issue_id)
action = []
completed_action_list = Action.objects.filter(issue = issue).exclude(state = Action.STATUS.PLANNED).exclude (state = Action.STATUS.IN_PROGRESS).exclude(is_historic = True).order_by("-event_date")
historic_action_list = Action.objects.filter(issue = issue).exclude(state = Action.STATUS.PLANNED).exclude (state = Action.STATUS.IN_PROGRESS).exclude(is_historic = False).order_by("-event_date")
planned_action_list = Action.objects.filter(issue = issue).exclude(state = Action.STATUS.COMPLETED).exclude(state = Action.STATUS.ABANDONED).order_by("-event_date")
actionlog_list = []
elif (issue_id is not None) and (action_id is not None):
action = get_object_or_404(Action, id=action_id)
issue = get_object_or_404(Issue, id=issue_id)
completed_action_list = Action.objects.filter(issue = issue).exclude(state = Action.STATUS.PLANNED).exclude (state = Action.STATUS.IN_PROGRESS).exclude(is_historic = True).order_by("-event_date")
historic_action_list = Action.objects.filter(issue = issue).exclude(state = Action.STATUS.PLANNED).exclude (state = Action.STATUS.IN_PROGRESS).exclude(is_historic = False).order_by("-event_date")
planned_action_list = Action.objects.filter(issue = issue).exclude(state = Action.STATUS.COMPLETED).exclude(state = Action.STATUS.ABANDONED).order_by("-event_date")
actionlog_list = ActionLog.objects.filter(action = action).order_by("-log_date")
else:
return HttpResponseNotFound('<h1>Page not found</h1>')
update_action_table = CompletedActionTable(reversed(completed_action_list), prefix="u")
historic_action_table = CompletedActionTable(reversed(historic_action_list), prefix="h")
planned_action_table = PlannedActionTable(planned_action_list, prefix="p")
if request.user.has_perm('srt.change_issuelist', issuelist):
actionlog_table = ActionLogTable(actionlog_list, prefix="l")
else:
actionlog_table = ActionLogTableUnEditable(actionlog_list, prefix="l")
RequestConfig(request, paginate={"per_page":20}).configure(issue_table)
RequestConfig(request, paginate=False).configure(update_action_table)
RequestConfig(request, paginate={"per_page":5}).configure(historic_action_table)
RequestConfig(request, paginate=False).configure(planned_action_table)
RequestConfig(request, paginate=False).configure(actionlog_table)
return render(request, 'srt/view_issues.html', {
'issuelist':issuelist ,
'issue': issue,
'action': action,
'issue_table':issue_table,
'update_action_table': update_action_table,
'historic_action_table': historic_action_table,
'planned_action_table': planned_action_table,
'actionlog_table': actionlog_table
})

Categories