Django Admin: Custom bulk duplication action not processing form data correctly

Title:

Django Admin: Custom bulk duplication action not processing form data correctly

Description:

I'm trying to implement a custom action in Django Admin to duplicate records in bulk for a model. The process should work as follows:

  1. Select multiple records in the Django Admin.
  2. Click on a custom action called "Duplicate selected records in bulk".
  3. A screen appears where the user can enter new effective dates (start and end).
  4. Upon clicking "Duplicate", new records are created, copying all fields from the original record except the effective dates, which are updated as entered by the user, and the liberado field, which should be set to False.

The issue I'm facing is that when I submit the form with the new dates, the duplication view does not seem to process the submitted data. The POST method is not being triggered correctly, and the form data is not captured.

When sending the created custom form, the request is not even falling into the view. The print which I placed is not being fired.

Here is the relevant code structure:

Model and Form:

class OrcamentoOpicional(models.Model):
    nome = models.CharField(max_length=100)
    categoria = models.ForeignKey(CategoriaOpcionais, on_delete=models.DO_NOTHING, null=True, blank=True)
    sub_categoria = models.ForeignKey(SubcategoriaOpcionais, on_delete=models.DO_NOTHING, null=True, blank=True)
    descricao = models.TextField()
    valor = models.DecimalField(decimal_places=2, max_digits=5, default=0.00)
    valor_final = models.DecimalField(decimal_places=2, max_digits=5, default=0.00, editable=False)
    inicio_vigencia = models.DateField()
    final_vigencia = models.DateField()
    liberado = models.BooleanField(default=False)

class DuplicarEmMassaForm(forms.Form):
    data_inicio = forms.DateField(label="Start Date", widget=forms.DateInput(attrs={'type': 'date'}))
    data_fim = forms.DateField(label="End Date", widget=forms.DateInput(attrs={'type': 'date'}))

Custom Admin Class with Bulk Duplication Action:

class DuplicarEmMassaAdmin(admin.ModelAdmin):
    actions = ['duplicar_em_massa']

    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('duplicar-em-massa/', self.admin_site.admin_view(self.duplicar_em_massa), name='duplicar_em_massa'),
        ]
        return custom_urls + urls

    def duplicar_em_massa(self, request, queryset):
        if request.method == 'POST':
            form = DuplicarEmMassaForm(request.POST)
            if form.is_valid():
                data_inicio = form.cleaned_data['data_inicio']
                data_fim = form.cleaned_data['data_fim']

                for item in queryset:
                    item.pk = None  # This sets the PK to None, creating a new record on save
                    item.inicio_vigencia = data_inicio
                    item.final_vigencia = data_fim
                    item.liberado = False
                    item.save()

                self.message_user(request, f"{queryset.count()} records duplicated successfully!")
                return redirect(request.get_full_path())
        else:
            form = DuplicarEmMassaForm()

        return render(request, 'admin/duplicar_em_massa.html', context={
            'items': queryset,
            'form': form,
            'title': "Duplicate records in bulk",
        })

HTML Template:

{% extends "admin/base_site.html" %}

{% block content %}
<h1>{{ title }}</h1>
<p>Confirm the new effective dates to duplicate the selected records.</p>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="hidden" name="aplicar" value="1">
    <button type="submit" class="button">Duplicate</button>
</form>
{% endblock %}

Issue:

  • When I submit the form, the POST request is not being processed correctly by the duplicar_em_massa view. The form seems to render correctly, but upon submission, Django does not capture or process the request data.
  • I've tried debugging with print statements, but the block that should handle the POST request does not execute after form submission.

Question:

  • Why is the Django Admin not processing the POST request correctly in my custom bulk duplication action? What might I be doing wrong in configuring this bulk duplication functionality?

I would appreciate any insights on what could be causing this issue and how to resolve it. Thank you!

  • Verified the template and form structure.
  • Ensured that the form includes the csrf_token.
  • Added print statements for debugging, but I only see the code execute when loading the page, not when submitting the form.
  • Checked that the form is being submitted via POST and that the HTTP methods are used correctly.
Back to Top