1

I am building an app that displays different courses. For each course there is a list of the different classes it has. Some courses have two classes, some have eight, some have just one or in the future some courses may have 10 classes. It's up to the app's administrator when they register a new course

class Curso(models.Model):
    clases = models.IntegerField(default=1)
    content = ArrayField(models.CharField(max_length=30),blank=False)

This model will only be for the administrator.

I want to store the different classes (just their names) in an array. But there's no need to show 8+ fields if the admin is just going to fill one in... Or is that the correct approach?

I want the admin to have an integer field where she types in how many classes the course has and depending on that the array fields will be displayed.

I understand ArrayField has a size attribute where I can say how long the array is. Right? So my question is:

Is there a way to dynamically change the array size depending on what the admin types in in the "clases" field?

I need this to work in the admin app. I am new to Django and I'm finding the admin app a little bit hard to manipulate.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
pauzca
  • 164
  • 1
  • 12

1 Answers1

1

Well I did my research. And this is how it turned out: enter image description here

models.py

from django.db import models
from django_better_admin_arrayfield.models.fields import ArrayField

# Create your models here.

class Course(models.Model):
     ...
    clases = ArrayField(models.CharField(max_length=10),null=True,blank=True, size=8)
    ...

Turns out I just needed to use ArrayField with django-better-admin-arrayfield It doesn't do exactly what I described in this question, but it works just as fine (even better) to visually edit the arrayfield in the admin page

Here's the repository django-better-admin-arrayfield

You just need to pip install it and then add it to your settings.py installed apps

INSTALLED_APPS = [
  ...
   'django_better_admin_arrayfield',
  ...

In admin.py

from django.contrib import admin
from .models import Course
from django_better_admin_arrayfield.admin.mixins import DynamicArrayMixin


@admin.register(Course)
class CursoAdmin(admin.ModelAdmin, DynamicArrayMixin):
    ...

And that was it! makemigrations and migrate and... It didn't work. The problem was the add another button wasn't working. So I read the issues in the repo and someone wrote you should run collectstatic and it worked!!

Shout out to @nbeuchat, whoever that is, that who's answer in in this stackoverflow post was the only thing that helped me get out of this problem

pauzca
  • 164
  • 1
  • 12