Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creating models based on the design developed last week on steps and flow #75

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions demo/demoapp/flow/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from django.urls import reverse

from django.forms.widgets import Widget
from django.utils.safestring import mark_safe

class RedirectButtonWidget(Widget):
def render(self, name, value, attrs=None, renderer=None):
action_url = reverse('actions')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hay que mejorar la definción de esta url porque es demasiado general, recomiendo utilizar "flow_actions" o algo similar.

Todas las urls de flujo pueden partir de "flow" por ejemplo:

path("flow", ...., name="index_flow"),
path("flow/create", ...., name="create_flow")
path("flow/actions", ...., name="actions_flow")

De esta manera separamos todas las urls relacionadas a flow y no chocamos con otras urls a futuro, porque sino a futuro nos vemos obligados a actualizarlas y revisar donde son llamadas y por ende nos quitaría tiempo de algo que podemos mejorar ahorita mismo.

button_html = f'<br> <a href="{action_url}" id="{name}_button" class="btn btn-primary hidden">Add Action</a>'
return mark_safe(button_html)


def save_steps(steps_data_json):
from djgentelella.forms.forms import GTStepForm
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esta importación del formulario GTStepForm no debe ir aquí.

for step in steps_data_json:
step_data = step['data']
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Como aseguras que esa clave data exista? Desde el navegador podemos modificar la data que enviamos al post de la función create_flow haciendo que la función el sistema caiga con errores, debemos validar ese campo stepsData ya sea con un formulario o con un serializador porque ahorita mismo resulta fácil sabotear la data del post al no haber validación de ello.


step_form_data = {
'name': step_data.get('name'),
'order': step_data.get('order'),
'status_id': [],
'form': [],
'pre_action': [],
'post_action': [],
}

form = GTStepForm(step_form_data)

if form.is_valid():
step_instance = form.save()

save_actions(step_data, step_instance)
print('exito')
else:
print(form.errors)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eliminar prints


def save_actions(step_data, step_instance):
from djgentelella.forms.forms import GTActionsStepForm
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Esta importación no debe ir acá.


if 'preActions' in step_data and step_data['preActions']:
for pre_action_data in step_data['preActions']:
pre_action_form = GTActionsStepForm(pre_action_data)
if pre_action_form.is_valid():
pre_action = pre_action_form.save()
step_instance.pre_action.add(pre_action)
else:
print(pre_action_form.errors)


if 'postActions' in step_data and step_data['postActions']:
for post_action_data in step_data['postActions']:
post_action_form = GTActionsStepForm(post_action_data)
if post_action_form.is_valid():
post_action = post_action_form.save()
step_instance.post_action.add(post_action)
else:
print(post_action_form.errors)
68 changes: 68 additions & 0 deletions demo/demoapp/flow/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import json

from django.shortcuts import render, redirect

from demoapp.flow.utils import save_steps
from djgentelella.forms.forms import GTStepForm, GTActionsStepForm, GTStatusForm, \
GTSkipConditionForm, GTFlowForm
from djgentelella.models import GTStep


def flow_index(request):
return render(request, 'gentelella/flow/flow.html')

def create_flow(request):

form = GTFlowForm()

if request.method == 'POST':
form = GTFlowForm(request.POST)
if form.is_valid():
form.save()
steps_data = request.POST.get('stepsData')
steps_data_json = json.loads(steps_data)
save_steps(steps_data_json)
return redirect('flow')

return render(request, 'gentelella/flow/create_flow.html', {'form': form})

def step_index(request, id):

step = GTStep()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Estas creando la instancia de un paso(GTStep) pero no estas logrando hacer nada con ella, porque en el código JS modificas los valores de los campos con lo exista en la sesión. Sino vas a guardar la instancia o hacer algo con ella entonces es mejor no pasarla.


form = GTStepForm(instance=step)
return render(request, 'gentelella/flow/step.html', {'form': form, 'id': id})

def actions_index(request):
if request.method == 'POST':
form = GTActionsStepForm(request.POST)
if form.is_valid():
form.save()
return redirect('flow')
else:
Copy link
Collaborator

@marcelagz marcelagz Oct 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Este else no es tan necesario puedes declarar el formulario apenas inicias la función para que quede por defecto, lo mismo para status y condition.

form = GTActionsStepForm()

return render(request, 'gentelella/flow/actions.html', {'form': form})


def status_index(request):
if request.method == 'POST':
form = GTStatusForm(request.POST)
if form.is_valid():
form.save()
return redirect('status')
else:
form = GTStatusForm()

return render(request, 'gentelella/flow/status.html', {'form': form})

def skip_condition_index(request):
if request.method == 'POST':
form = GTSkipConditionForm(request.POST)
if form.is_valid():
form.save()
return redirect('success_url')
else:
form = GTSkipConditionForm()

return render(request, 'gentelella/flow/skip_conditions.html', {'form': form})
27 changes: 27 additions & 0 deletions demo/demoapp/templates/gentelella/flow/actions.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{% extends 'gentelella/base.html' %}
{% load gtsettings timejs %}

{% block content %}
<div class="card">
<div class="card-body">
<div class="card-title titles">
<h2>Actions</h2>
</div>


<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button class="btn btn-primary text-end" type="submit">Submit</button>
</form>

</div>
</div>
</div>
{% endblock %}

{% block js %}

<script></script>

{% endblock js%}
38 changes: 38 additions & 0 deletions demo/demoapp/templates/gentelella/flow/create_flow.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{% extends 'gentelella/base.html' %}
{% load gtsettings timejs %}

{% block content %}
<div class="card">
<div class="card-body">
<div class="card-title titles">
<h2 id="step-title">Create Flow</h2>
</div>

<form method="post" id="flow_form" action="{% url 'create_flow' %}">
{% csrf_token %}
{{ form.as_p }}
<input type="hidden" id="stepsData" name="stepsData">

<button class="btn btn-primary" id="create_flow" type="submit">Submit</button>
</form>
</div>
</div>
</div>
{% endblock %}

{% block js %}

<script>

document.getElementById('create_flow').addEventListener('click', function() {
event.preventDefault();
var stepsData = JSON.parse(sessionStorage.getItem('stepData')) || {};
console.log(stepsData);
document.getElementById('stepsData').value = JSON.stringify(stepsData);
document.getElementById('flow_form').submit();
sessionStorage.clear();
});

</script>

{% endblock js%}
Loading