0

I have classes like this:

class Building(models.Model):
    name = models.CharField(max_length=10)
    floors= models.IntegerField()

    def __str__(self):
        return self.name

class BuidingAccessRole(models.Model):
    role_name = models.CharField(max_length=10)  #name for the role of accessing a floor of one building
    building = models.ForeignKey(building,on_delete=models.CASCADE)
    floor = models.IntegerField()   Note:#i want this floor to be shown as choicefield with count starting from 1 to (building.floors) and get saved as integer value in database.
    def __str__(self):
       return self.name

  """If we set Building admin page as this object : 
       name='b1'
       floors=3
  then :
  BuidingAccessRole admin page to be shown as 
       name='Access for floor'
       building = b1 or 1 as 'id'
      floor shown as <select>1,2,3 as option </select>""" 

Note:#i want BuidingAccessRole.floor to be shown as choicefield in admin page with count starting from 1 to (building.floors) and get saved as integer value in database.
i tried acheiving this using chained foreign key but doesnt work out in this case .Is there any other way to do this!

  • Override the `form` so that the `ModelAdmin` uses your own `ModelForm` (see [here](https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form)). Then in your form, you can make `floor` a `ChoiceField` and in its `__init__` method set the choices to what you need. – dirkgroten Dec 16 '19 at 17:11
  • but i want my choices to come as selected building objects floor value. – akshay mishra Dec 16 '19 at 17:17
  • why but? As I say, you can do that in the `__init__` method of the form. `self.fields['floor'].choices = range(1, self.instance.building.floors + 1)` or something similar – dirkgroten Dec 16 '19 at 17:19
  • i tried doing this as adviced , created the git repository for the same (https://github.com/akshaymishra5395/dependent) but admin save is not working to save the changed values of the list ... – akshay mishra Dec 17 '19 at 17:22
  • Pls try solving this... – akshay mishra Dec 22 '19 at 01:31

0 Answers0