Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django custom model save() method for a non-persisted attribute

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading