0

I currently have a Base64ImageField which works totally fine. The only problem I am having is sometimes it returns back an incomplete path. It skips the domain name but the rest of the path is fine.The reason its skipping the domain name is because I do not pass in the parameter context={"request": request} during serialization.The reason for that is because sometimes I do not have access to the request object.In other words this works fine

jsonObject = Serializer(model_instance,context={"request": request}).data 

and this one skips the domain name from the image field

jsonObject = Serializer(model_instance).data 

My question is how can I make it return the full url path using the second example when I do not have to the request object ? Or is there any way for me to obtain the request object. When its not available ?

I have this serializer in my code

class Serializer_Employer_TX(ModelSerializer): user = Serializer_User() employer_image = Base64ImageField(max_length=None, use_url=True, required=False) class Meta: model = modelEmployer fields = [ 'user', 'employer_zip', 'employer_image', ] 

1 Answer 1

1

You can use sites framework, and override to_representation method of Serializer_Employer_TX

from django.contrib.sites.models import Site class Serializer_Employer_TX(ModelSerializer): user = Serializer_User() employer_image = Base64ImageField(max_length=None, use_url=True, required=False) class Meta: model = modelEmployer fields = [ 'user', 'employer_zip', 'employer_image', ] def to_representation(self, instance): """Convert `username` to lowercase.""" ret = super().to_representation(instance) if not 'request' in self.context: # You can tweaks the url in here directly current_site = Site.objects.get_current().domain ret['employer_image'] = current_site + ret['employer_image'] return ret 

I hope this will help.

Sign up to request clarification or add additional context in comments.

3 Comments

This sounds promising could you tell me what to_representation does ? and when its called ?
Let me try that and get back to you
@Rajeshwar to_representation() - provided by BaseSerializer and ModelSerializer. Override this to support serialization, for read operations. more implementation details here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.