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.

====Page.html====

<h5>Documents</h5>
</div>
<div class="row">
  <div class="col-md">
    <div class="card card-body">
      <table class="table table-sm">
        <tr>
          <th>#</th>
          <th>Nom du fichier</th>
          <th>Fichier</th>
          <th></th>
        </tr>

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

====view.py====

# Button to add docs
@login_required(login_url='loginpage')
@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():
            forms.save()
            return redirect('/employe')

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

====Models.py====

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)

====Form.py====

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 %}
  <tr>
    <td>{{ forloop.counter }}</td>
    ...
  </tr>
{% 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