在Django中提交时,如何防止更新模式在数据库中创建新条目?

时间:2019-11-26 16:39:20

标签: javascript python html django modal-dialog

我有一个跟踪用户何时输入/离开区域的表单。例如,如果用户输入一个区域,然后忘记“离开”该区域并尝试输入另一个区域,则先前的输入将被标记为N,并且模态将提示用户输入以下内容的“估计时间”当他们认为自己离开了先前的区域时。

我遇到的问题是,模式在提交时正在创建一个新条目,而我无法弄清楚这是在哪里发生以及如何防止它。这也导致逻辑也标记了较新的条目,并且基本上只是要求一次“估计时间”。

进行视觉解释;这是有人进入区域时的第一次提交。

enter image description here

然后在这里,我输入另一个而不退出第一个,则标记该条目,然后模态提示我(这是在提交模态之前)。到目前为止,一切都在相应地进行。

enter image description here

然后,当我提交模态时,会发生以下情况: enter image description here

在我点击提交之后,它也一直出现并更新下一个条目,这是因为提交模态时创建的新条目也被标记了。我似乎无法弄清楚如何获取每次提交时都不会将其保存为新条目的模式。

我在休假区遇到同样的问题,但是由于逻辑相似,所以我只在下面输入回车区号。 views.py中的enter_without_exit变量是触发html方式调用的原因。

views.py

def enter_exit_area(request):
    enter_without_exit = None
    exit_without_enter = None

    if request.method == 'POST':
        form = WarehouseForm(request.POST)
        if form.is_valid():
            emp_num = form.cleaned_data['employee_number']
            area = form.cleaned_data['work_area']
            station = form.cleaned_data['station_number']

            if 'enter_area' in request.POST:
                new_entry = form.save()
                EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now())

                # If employee has an entry without an exit and attempts to enter a new area, mark as an exception 'N'
                enters_without_exits = EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num) & Q(time_out__isnull=True) & Q(time_exceptions="")).exclude(pk=new_entry.pk).order_by("-time_in")
                if len(enters_without_exits) > 0:
                    enter_without_exit = enters_without_exits[0]
                    enters_without_exits.update(time_exceptions='N')

                message = 'You have entered %(area)s' % {'area': area}
                if station is not None:
                    message += ': %(station)s' % {'station': station}
                messages.success(request, message)
                form = WarehouseForm()

    else:
        form = WarehouseForm()
    return render(request, "operations/enter_exit_area.html", {
        'form': form,
        'enter_without_exit': enter_without_exit,
        'exit_without_enter': exit_without_enter,
    })


class UpdateTimestampModal(CreateUpdateModalView):
    main_model = EmployeeWorkAreaLog
    model_name = "EmployeeWorkAreaLog"
    form_class = UpdateTimestampModalForm
    template = 'operations/modals/update_timestamp_modal.html'
    modal_title = 'Update Missing Time'

models.py

class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model):
    employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False)
    work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area")
    station_number = models.ForeignKey(Station, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True)
    edited_timestamp = models.DateTimeField(null=True, blank=True)
    time_exceptions = models.CharField(max_length=2, blank=True, default='', choices=EXCEPTION_STATUS)
    time_in = models.DateTimeField(help_text="Time in", null=True, blank=True)
    time_out = models.DateTimeField(blank=True, help_text="Time out", null=True)

forms.py

class WarehouseForm(AppsModelForm):
    class Meta:
        model = EmployeeWorkAreaLog
        widgets = {
            'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}),
        }
        fields = ('employee_number', 'work_area', 'station_number')


class UpdateTimestampModalForm(AppsModelForm):
    def __init__(self, *args, **kwargs):
        super(UpdateTimestampModalForm, self).__init__(*args, **kwargs)
        self.fields['edited_timestamp'].widget.format = '%m/%d/%Y %I:%M %p'
        self.fields['edited_timestamp'].input_formats = ['%m/%d/%Y %I:%M %p']

    class Meta:
        model = EmployeeWorkAreaLog
        fields = ('edited_timestamp',)

    def clean_edited_timestamp(self):
        edited_stamp = self.cleaned_data.get('edited_timestamp')
        return edited_stamp

enter_exit_area.html

{% extends "base.html" %}
{% load core_tags staticfiles %}
{% block head %}
    <script src="{% static "js/operations/warehouse_enter_exit.js" %}"></script>
{% endblock head %}

{% block main %}

    {% if enter_without_exit %}
        <div id="auto-open-ajax-modal" data-modal="#create-update-modal" data-modal-url="{% url "operations:update_timestamp_modal" enter_without_exit.id %}" class="hidden"></div>
    {% endif %}
    {% if exit_without_enter %}
        <div id="auto-open-ajax-modal" data-modal="#create-update-modal" data-modal-url="{% url "operations:update_timestamp_modal" exit_without_enter.id %}" class="hidden"></div>
    {% endif %}

    <form id="warehouseForm" action="" method="POST" novalidate >
        {% csrf_token %}

        <div>
            <div>
                <div>{{ form.employee_number.errors.as_text }}</div>
                <label>Employee #</label>
                {{ form.employee_number }}
            </div>

            <div>
                <div>{{ form.work_area.errors.as_text }}</div>
                <label>Work Area</label>
                {{ form.work_area }}
            </div>
            <div>{{ form.station_number.errors.as_text }}</div>
            <div>
                <label>Station</label>
                {{ form.station_number }}
            </div>
        </div>

        <div>
            <div>
                <button type="submit" name="enter_area" value="Enter">Enter Area</button>
                <button type="submit" name="leave_area" value="Leave">Leave Area</button>
            </div>
        </div>
    </form>

    {% modal id="create-update-modal" title="Update Timestamp" primary_btn="Submit" default_submit=True %}
{% endblock main %}

update_timestamp_modal.html

{% load core_tags %}

<form id="create-update-form" method="post" action="{% url "operations:update_timestamp_modal" main_object.id %}">
    {% csrf_token %}

    <label>Update</label>
    <div class="row">
            <div class="form-group col-xs-6">
                {% standard_input form.edited_timestamp datetimepicker=True hide_label=True %}
            </div>
    </div>
</form>

0 个答案:

没有答案