0

I'm trying to get Django automatically add a field to an object where the date and time is saved in the field as a timestamp.

When I create the object in my view and I go check in admin page, every other field is created but not this one.

views.py :

newconf = ConfigUser.objects.create(
        ref=''.join(random.SystemRandom().choice(
            string.ascii_lowercase + string.ascii_uppercase + string.digits
        ) for _ in range(20)),
        name='',
        user=request.user,
        # Here I don't add created_at because I want it to be automatic (see models.py)
        cpu=cpu[0],
        gpu=gpu[0],
        ram=ram[0],
        ssd_m2=ssd_m2[0],
    )

models.py :

class ConfigUser(models.Model):

    ref = models.CharField(max_length=20, unique=True, default='')
    name = models.CharField(max_length=128, default='')
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    cpu = models.ForeignKey(CPU, on_delete=models.CASCADE)
    gpu = models.ForeignKey(GPU, on_delete=models.CASCADE)
    ram = models.ForeignKey(RAM, on_delete=models.CASCADE)
    ssd_m2 = models.ForeignKey(SSD_M2, on_delete=models.CASCADE)

    def __str__(self):
        return self.name
Mike Delta
  • 726
  • 2
  • 16
  • 32

2 Answers2

0

If a field inside model is created with auto_now attribute set, it will also include the property editable=False and therefore it will not show up in the admin panel.

To overcome this, you need to override your save method:

class ConfigUser(models.Model):
    # some code
    created_at = models.DateTimeField(editable=False)
    
    def save(self, *args, **kwargs):
        if not self.id:
            self.created_at = timezone.now()
        return super(User, self).save(*args, **kwargs)
Jarvis
  • 8,494
  • 3
  • 27
  • 58
  • 1
    Much simpler is just to add that field into read_only fields as this is already answered should be closed as duplicate – iklinac Dec 26 '20 at 13:17
-1

First of all, make sure to check if all model migrations have been done. Secondly, as an alternative, you could try to create the "newconf" object from the class directly, and not via the objects.create() method, like so:

# Create the record as object of the model class
newconf = ConfigUser(ref=''.join(random.SystemRandom().choice(
            string.ascii_lowercase + string.ascii_uppercase + string.digits
            ) for _ in range(20)),
            name='',
            user=request.user,
            cpu=cpu[0],
            gpu=gpu[0],
            ram=ram[0],
            ssd_m2=ssd_m2[0])

newconf.save()

To have this method working you should only add the def__init__ method in the model ConfigUser, passing all the initialization parameters in.

BeGeos
  • 29
  • 8