Converting inline javascript to Alpine.js - javascript

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>

Related

When using Fetch the page reloads (when it shouldn't) and only shows the Json data instead of the page that should be displayed

I am trying to make a basic twitter style application for a class project. When the like button is clicked the text in the button should then change to say unlike and the like count should increase by one without reloading the page. The database information is updated. The page itself reloads to a white background and the only thing on the page is my json data "{"likeButton": "Unlike", "total_likes": 0}", instead of the page itself. Any help would be appreciated.
Edit: here is a screenshot of the result I am getting
webpage screenshot
views.py
#login_required
def likes(request, post_id):
try:
current_user = request.user
post = Post.objects.get(id = post_id)
likeCount = Post.objects.get(id = post.id)
total_likes = likeCount.like_count
likeButton = request.POST.get('buttonForLikes')
if likeButton == 'Like':
total_likes = total_likes + 1
post.like_count = total_likes
post.save()
post.like.add(current_user)
post.save()
else:
total_likes = total_likes - 1
post.like_count = total_likes
post.like.remove(current_user)
post.save()
return JsonResponse ({'likeButton': likeButton, 'total_likes': total_likes,}, status=200,)
except KeyError:
return HttpResponseBadRequest("Like Error")
urls.py
from django.urls import path
from . import views
app_name = "network"
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("new-post", views.new_post, name="new-post"),
path("profile/<str:username>", views.profile, name="profile"),
path("follows/<str:username>", views.follows, name="follows"),
path("following", views.following, name="following"),
path("edit", views.edit, name="edit"),
path("likes/<int:post_id>", views.likes, name='likes')
]
HTML
{% extends "network/layout.html" %}
{% load static %}
{% block body %}
{% if user.is_authenticated %}
<div class="borderDiv">
<div class="newPostCard">
<form id = "new_post_form" name="newPost" action = "{% url 'network:new-post' %}" method ="POST">
{% csrf_token %}
<label id="test"><h2>New Post</h2></label><br>
<textarea id="newPostBox" name="newPost"></textarea></textarea><br><br>
<input type ="submit" id = "new_post_submit" class = "btn btn-primary">
</form>
</div>
</div>
{% endif %}
<div class="newPostCard">
{% for item in all_post %}
<div class="borderDiv">
<div class="newPostCard">
<h2>{{ item.user }}</h2>
<p id="user_post">{{ item.post }}</p>
</div>
<form id = "like_form" method ="POST" action = "{% url 'network:likes' item.id %}" >
{% if request.user in item.like.all %}
<div> <button claas="likes" id = 'likeButton' data-id= '{{ item.id }}' value="Unlike" name="buttonForLikes">
Unike</button>: <span id="numOfLikes">{{ item.like_count }}</span>
{% csrf_token %}
</div>
{% else %}
<div> <button class="likes" id = 'likeButton' data-id= '{{ item.id }}' value="Like" name="buttonForLikes">
Like</button>: <span id="numOfLikes">{{ item.like_count }}</span>
{% csrf_token %}
</div>
{% endif %}
</form>
<div>
{% if user.is_authenticated and request.user == item.user %}
<button class ="btn btn-primary" id="edit">Edit</button>
{% endif %}
<textarea id="editText" name="editBox" style="display: none;"></textarea>
<button class="btn btn-primary" id="editSaveButton" style="display: none;">Save</button>
</div>
<p><i>{{ item.timestamp }}</i></p>
</div>
</div>
{% endfor %}
<div id="page_num">
<span class="page_numbers">
{% if all_post.has_previous %}
« first
previous
{% endif %}
<span class="current_page">
Page {{ all_post.number }} of {{ all_post.paginator.num_pages }}.
</span>
{% if all_post.has_next %}
next
last »
{% endif %}
</span>
</div>
</div>
<script src="{% static 'network/edit.js' %}"></script>
<script src="{% static 'network/likes.js' %}"></script>
{% endblock %}
javascript
let likes = document.getElementById('likeButton');
likes.addEventListener("click", (e) =>{
e.preventDefault();
e.stopPropagation();
let likeCount = document.getElementById('numOfLikes');
fetch(`/likes/${likes.dataset.id}`, {
credentials: "include",
method: "PUT",
headers: {
"Accept": "application/json",
'Content-Type': 'application/json',
},
})
.then(response => response.text())
.then(result => {
if (result.likeButton === 'Like'){
likes.innerHTML = "Unlike";
likeCount.innerHTML = result.total_likes;
}
else{
likes.innerHTML = 'Like';
likeCount.innerHTML = result.total_likes;
}
})
return false;
});

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>

Reload the page after clicking a form button in IE

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

django javascript template conditional test

I am looking to do conditional tests in the html part of my code
html
<p class= "rep3" width="100" id="val1" data1={{ family }} style= "display:none;">{{ family }}</p>
<p class= "rep4" width="100" id="val2" data2="" style= "display:none;"></p>
{% if data2 == "general" %}
criteria1
{% else %}
{% if data2 == "ceramic" %}
criteria2
{% else %}
criteria
{% endif %}
{% endif %}
javascript
<script type="text/javascript">
$(document).ready(function() {
var element = document.getElementById('val1');
laval1 = element.getAttribute('data1');
var element2 = document.getElementById('val2');
element2.setAttribute('data2', laval1);
});
</script>
I read data1 in the script
I would like to send this data in data2 and after to do the test
but its not working
How to do that ?
This code won't work because:
JavaScript code is run by the client, long after the template tags ({% if data2 == "general" %} etc. ) are compiled in the server.
You can't send data from JS to django like that for data2. (Although you could use AJAX), but that is not required in this case.
Why don't you could do something like this, instead of relying on Javascript?
<p class= "rep3" width="100" id="val1" data1={{ family }} style= "display:none;">{{ family }}</p>
<p class= "rep4" width="100" id="val2" data2="" style= "display:none;"></p>
{% if family == "general" %}
criteria1
{% else %}
{% if family == "ceramic" %}
criteria2
{% else %}
criteria
{% endif %}
{% endif %}

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