0

In django project, I created a default function called "create_code" to randomly generate a default value for "code" field in models.py file.

# models.py
class Project(models.Model):
    name = models.CharField("Project name", max_length=255)
    code = models.CharField("Code", max_length=10, default=create_code, editable=False)

In admin.py file, I set "code" as a readonly_field.

#admin.py
@admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
    fields = ('name', 'code')
    readonly_fields = ('code', )

The problem occours when I create a new Project object in admin page. The default value for "code" appers (eg. ABCD), but when I save the data this value change to another one (eg. EFGH). I think two objects are been created: one when loads the page and other when save the data.

How can I read the "code" value from first object to overwrite the last one and save "ABCD" instead of "EFGH"?

1 Answers1

0

if you want to just create a random code when an object is created,the better way is to use this function in your model and this can fix your problem: first create a method to generate a random number like this :

def generate_ref_code():
    code = str(uuid.uuid4()).replace("-","")[:12]
    return code

then put this function in your Project class model:

 def save(self, *args, **kwargs):
        if self.code == "":
            code = generate_ref_code()
            self.code = code
        super().save(*args, **kwargs)

or the simpler implementations is like this :

 def save(self, *args, **kwargs):
        code = str(uuid.uuid4()).replace("-","")[:12]
        self.code = code
        super(Project, self).save(*args, **kwargs)

and dont forget to set blank='true' to your Code field so you can save a blank code and this randomly generates a code to your field

  • In this case, the inital value for "code" in admin page will be blank and the random value will set only when I save the object. I want to see the random value in "admin/project/add" page for "code" field before save. Is this possible? – Bismarck Gomes May 27 '21 at 19:05
  • you are right in this case you cant see your code before saving,to fix this issue you can use pre_save signal.this should fix your problem and this is the link that can help you https://stackoverflow.com/questions/6461989/populating-django-field-with-pre-save – amir moshfeghi May 27 '21 at 20:15
  • I belive pre_save signal is not emmited when the form in admin page is loaded. I can use pre_save to overwrite the "code" variable, but how can I save the "ABCD" value (inital value for "code" in add page) to use in pre_save? – Bismarck Gomes May 27 '21 at 20:29