user1778743
user1778743

Reputation: 363

How to pre-fill a modelform field DJango

ive been searching for a while for information on how to do this. here is my situation. i have a ContactForm(form.ModelForm): and it excludes the ID field

which i want to be auto generated based on the last entry to the Contact table

but im not finding any examples on how to do this the help im lookin for is how to enter information without being visible to the user while at the same time automatically pre-fill the right id and i cant use pk cause it has a foriegn key to another table

Upvotes: 0

Views: 339

Answers (1)

Kostas Pelelis
Kostas Pelelis

Reputation: 1342

If you define a field of a model as an AutoField it will do this exact thing

EDIT:

If you want to define a custom auto incrementing ID you can do it like: from django.db import models

class MyModel(models.Model):
    _id_counter = 0
    custom_id = models.IntegerField()

    @classmethod
    def create(cls):
        my_model = cls(custom_id=MyModel._id_counter)
        MyModel._id_counter += 1
        return my_model

model1 = MyModel.create()

Upvotes: 1

Related Questions