Django automatically add number in table

I would like when I add a file in the table it automatically adds a number from 1. I cannot use the primary key in the model because I already use it. anyone have a solution. thank you.


<div class="row">
  <div class="col-md">
    <div class="card card-body">
      <table class="table table-sm">
          <th>Nom du fichier</th>

        {% for d in document %}
            <td><a download href="{{d.Fichier.url}}">{{d.Fichier}}</a></td>
            <td><a class="btn btn-outline-danger" href="{% url 'supprimerdocument' %}">Supprimer</a>
        {% endfor %}

# Button to add docs
@allowed_users(allowed_roles=['admin', 'livraison'])
def createDocument(request):
    forms = documentForm()

     if request.method == 'POST':
        forms = documentForm(request.POST, request.FILES)
        if forms.is_valid():
            return redirect('/employe')

    context = {'forms':forms}
    return render(request, 'accounts/document_form.html', context)

class Document(models.Model):
    employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL)
    Number = models.IntegerField(default=1)
    Description = models.CharField(max_length=100, null=True)
    Fichier = models.FileField(upload_to='documents/')
    data_created = models.DateTimeField(auto_now_add=True, null=True)

class documentForm(ModelForm):
    class Meta:
        model = Document
        fields = '__all__'
        exclude = ['Number']

You can use forloop.counter in your template to access the (1-indexed) iteration of the for loop

{% for d in document %}
    <td>{{ forloop.counter }}</td>
{% endfor %}

It looks like you can do an AutoField as per How do I make an auto increment integer field in Django?

But as a fallback: You could just do an Integer field and override the modelform's .save() method and auto fill it like self.some_field = Document.objects.all().count()
..if you do that, best to add a flag for if it's an edit form or not.. I believe you can do that with if self.instance: if true, is edit form

use callable default

def get_next_number():
    max_val = Document.objects.aggregate(models.Max('Number'))['Number__max'] or 0
    return max_val + 1

class Document(models.Model):
    Number = models.IntegerField(default=get_next_number)
Back to Top