Django: How to prevent date field conflicts in admin

Asked

Viewed 30 times

1

In a record of a Vaga inside the Django admin I have two fields: data_inicio and data_fim.

inserir a descrição da imagem aqui

But I wish it wasn’t possible to put one data_fim less than data_inicio, and I don’t know how it can be done in the Django admin. The code of the vacancy admin lies like this:

@admin.register(Vaga)
class VagaAdmin(admin.ModelAdmin):
    list_display = ('titulo', 'data_inicio', 'data_fim')

If anyone has a sense of how this can be done, or any link that might help, I would be grateful.

1 answer

4


You can create a form with validation

Please modify the Vagaadmin

@admin.register(Vaga)
class VagaAdmin(admin.ModelAdmin):
    form = VagaForm
    list_display = ('titulo', 'data_inicio', 'data_fim')

Create Form with validation

class VagaForm(forms.ModelForm):
    class Meta:
        model = Vaga

    def clean(self):
        data_inicio = self.cleaned_data.get('data_inicio')
        data_fim = self.cleaned_data.get('data_fim')
        if data_inicio > data_fim:
            raise forms.ValidationError("Data de início posterior a data fim")
        return self.cleaned_data
  • 1

    Hi paulo, I arrived at a similar solution earlier, but in the Meta class I added Fields. I will mark the answer as a solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.