koichi_n
koichi_n

Reputation: 107

How to differentiate capital and small letters in using Django admin "prepopulated_fields"?

I'm going to use 'prepopulated_fields' at Django admin to get a YouTube embed code from its video id, as below.

class VideoAdmin(admin.ModelAdmin):
prepopulated_fields = {"embed_code": ("embed_id",)}
inlines = (CourseVideoInline,)

but embed_code I can get from "Rmp6zIr5y4U" is "rmp6zir5y4u", all capital letters changed into small ones.

Have any ideas to solve this?
or is any better ways to get embed code from video id by customizing Django admin?

Thanks! Video model (related fields) is below.

class Video(models.Model):    
  embed_code = models.TextField(max_length=1000)
  embed_id = models.CharField(max_length=200)

Upvotes: 0

Views: 533

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

prepopulated_fields are mainly used for generating slugs from titles via javascript - hence why you see it in lowercase. You might be better off overwriting the models save function so that when an instance of your model is saved, it can grab the video_id and generate the embed_code:

class MyModel(models.Model):
     video_id = ...
     embed_code = ...

     def save(self, *args, **kwargs):
         # If we have enetered a video id, but there is not saved embed code, generate it
         if not self.embed_code and self.video_id:
             self.embed_code = "http://youtube.com/%s" % self.video_id
         super(MyModel, self).save(*args, **kwargs)

an alternative is to do this at the admin view level (as opposed to the model level). You could do this by overwriting the save_model method of the ModelAdmin class. This gives you the added bonus of having access to the request and the form:

class MyModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        video_id = forms.cleaned_data.get('video_id', None)
        # If we are creating the object, and the video id is present
        if video_id and not change:
            obj.embed_code = video_id
        obj.save()

This code is untested, it's just to illustrate the two places you might want to achieve what you are looking to do

Upvotes: 1

Related Questions