Home > Software engineering >  Django custom model save() method for a non-persisted attribute
Django custom model save() method for a non-persisted attribute

Time:08-19

In Django 4 custom model save() method, how do you pass a form non-persistent form value?

For example:

The model form below has the non-persistent field called client_secret.

class ClientModelForm(forms.ModelForm):
    client_secret = forms.CharField(initial=generate_urlsafe_uuid)

This field will never be saved, it is auto-generated and will be required to make a hash for a persisted field in my model save() method.

class Client(models.Model):
    client_hash = models.BinaryField(editable=False, blank=True, null=True)

    def save(self, *args, **kwargs):
        """ Save override to hash the client secret on creation. """
        if self._state.adding:
            "GET THE CLIENT SECRET FROM THE FORM"
            client_hash = make_hash_key(client_secret)
            self.client_hash = client_hash

How do I get the client secret value from the form above code example? Is this the most appropriate approach?

CodePudding user response:

You would need to call the super class' save method at the end like so:

super(Client, self).save(*args, **kwargs)

For saving the form, you would need to add a model to the modelform's Meta class, and you would need to add the following logic into a view:

form = Form(request.METHOD)
if form.is_valid():
    uuid = form.instance.client_secret
    form.save()

Where form would look like:

class ClientForm(forms.ModelForm):
    fields...
    class Meta:
        model = ClientModel

Highly recommend taking a look at the docs

Edit

To get the logic into the model save, you could pass it into the kwargs of the save, save(client_secret=client_secret), and then in the save method you could try:

self.field = kwargs.get('client_secret')

then when saving the form, as shown above, you could do

save(client_secret=uuid)
  • Related