Home > Blockchain >  how to set a default value for a field model to another model field
how to set a default value for a field model to another model field

Time:10-21

here are models.py file

class album(TimeStampedModel):
    #album_artist = models.ForeignKey(artist, on_delete=models.CASCADE)
    album_name = models.CharField(max_length=100, default="New Album")
    #released_at = models.DateTimeField(blank=False, null=False)
    #price = models.DecimalField(
     #   max_digits=6, decimal_places=2, blank=False, null=False)
    #is_approved = models.BooleanField(
     #   default=False, blank=False)

    #def __str__(self):
    #    return self.album_name


class song(models.Model):
    name = models.CharField(max_length=100,blank=True,null=False)
    album = models.ForeignKey(album, on_delete=models.CASCADE,default=None)
    # image = models.ImageField(upload_to='images/', blank = False)
    # thumb = ProcessedImageField(upload_to = 'thumbs/', format='JPEG')
    # audio = models.FileField(
        # upload_to='audios/', validators=[FileExtensionValidator(['mp3', 'wav'])])
    # def __str__(self):
        # return self.name

I want to make the default value of the song name equal to the album name which i choose by the album Foreignkey. (in the admin panel page) any help ?

CodePudding user response:

Provided the song name is set to blank=True. You can create a pre_save signal to set the name.

...

from django.db.models.signals import pre_save
from django.dispatch import receiver

....

@receiver(pre_save, sender=Song)
def song_pre_save(sender, instance, **kwargs):
    if instance.name is None:
        album = Album.object.get(pk=instance.album)
        instance.name = album.album_name
  

You can read more on the Django website

CodePudding user response:

Because you're album model's __str__ method is just self.name this is possible, (else the option text wouldn't be correct) ..you have to override Song's Admin change_form template

You need to create the file change_form.html in this path, create all the folders: templates/admin/{app_name}/song/change_form.html

  • {app_name} = the folder name where Song's model.py is located

change_form.html

  • You can't override just the add_form.html, so i've added an if so it'll skip the field if it already has a value (for actual change forms)
{% extends "admin/change_form.html" %}

{% block extrahead %}{{ block.super }}
<script src="{% url 'admin:jsi18n' %}"></script>
{{ media }}

<script>
  django.jQuery(function($) { // Use Django's included Jquery
    // Default form format `id_{fieldname}`
    $('#id_album').change(function(){
      if ($('#id_name').val() == ''){
        // $(this).val() would be pk, so we need to find the selected option and use it's text
        $('#id_name').val($(this).find('option:selected').text());
      };
    });
  });
</script>
{% endblock %}

I wasn't sure on what Block I should override, so I picked extrahead .. there might be better ones, but that's the only one the popped out at me and made sense

  • Related