Beno
Beno

Reputation: 576

Is it possible to disable a field in Django admin?

I give you my example right now because it's too hard to explain it, well, I don't know XD. I have an object named Step like this :

class Step(models.Model):
    # Intitulé de la question
    title = models.CharField(max_length=300)
    # Appartenance
    belonging = models.ForeignKey('Survey', blank=True, null=True)
    # Renvoi à lui-même pour arborescence
    parent = models.ForeignKey('self', blank=True, null=True)
    # Ordre de la réponse
    order = models.PositiveIntegerField(default=0)
    # Complément d'information
    add_info = models.TextField(blank=True, verbose_name="Additional informations")

    def __str__(self):
        return (self.title)

    def children(self):
        return Step.objects.filter(parent=self, belonging=self.belonging).order_by('order', 'title')

    def render_step(self):
        template = get_template('app_questionnaire/_step.html')
        return template.render({'step': self})

I have one Step without parent and only one. I just wonder if it's possible to disable the EMPTY parent field in the Django admin after adding a Step ? I would like to add others Step with a parent but not another Step without a parent. I don't know if you know what I mean :)

Thank you in advance !

Upvotes: 4

Views: 5161

Answers (4)

Beno
Beno

Reputation: 576

I would like to thank @Peter for his answer, I just adapted the code with my problem so I give it if anyone is in need !!

class StepAdmin(admin.ModelAdmin):

      def get_form(self, request, obj=None, **kwargs):
           form = super(StepAdmin, self).get_form(request, obj, **kwargs)

           if Step.objects.filter(parent__isnull=True).count() > 1:

                # this will hide the null option for the parent field
                form.base_fields['parent'].empty_label = None

           return form

Upvotes: 1

Peter Sobhi
Peter Sobhi

Reputation: 2550

You can do this by overriding the get_form method in you ModelAdmin:

class StepModelAdmin(admin.ModelAdmin):

    def get_form(self, request, obj=None, **kwargs):
        form = super(StepModelAdmin, self).get_form(request, obj, **kwargs)

        if Step.objects.count() > 1:

            # this will hide the null option for the parent field
            form.base_fields['parent'].empty_label = None

        return form

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

You can override the save method in the models

Ex:

def save(self):
    if Step.objects.count() > 1:
        if not self.parent:
            print("Error")
        else:
            super(Step, self).save()

Upvotes: 1

py-D
py-D

Reputation: 669

I am not exactly getting what you want to do but yahh you can exclude field or declare particular field as read only:

class StepOver(admin.TabularInline):
       model = Step
       exclude = ['parent']
       readonly_fields=('parent', )

Upvotes: 6

Related Questions