user1778743 user1778743 - 1 year ago 160
Python Question

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

Answer Source

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


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()

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

model1 = MyModel.create()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download