What is the best way to serialize a method within a model?

Is there a way to serialize the get_picture(self) method within this model? I am currently working on a social networking project and I need to serialize this method in order to obtain a JSON URL for the user's profile picture to be utilized in an Android application.

class Profile(models.Model):
     user = models.OneToOneField(User)
     location = models.CharField(max_length=50, null=True, blank=True)
     url = models.CharField(max_length=50, null=True, blank=True)
     job_title = models.CharField(max_length=50, null=True, blank=True)

     class Meta:
         db_table = 'auth_profile'

     def __str__(self):
         return self.user.username

     def get_url(self):
         url = self.url
         if "http://" not in self.url and "https://" not in self.url and len(self.url) > 0:  # noqa: E501
            url = "http://" + str(self.url)

         return url

     def get_picture(self):
         no_picture = 'http://trybootcamp.vitorfs.com/static/img/user.png'
         try:
            filename = settings.MEDIA_ROOT + '/profile_pictures/' +\
                self.user.username + '.jpg'
            picture_url = settings.MEDIA_URL + 'profile_pictures/' +\
                self.user.username + '.jpg'
            if os.path.isfile(filename):
               return picture_url
            else:
                gravatar_url = 'http://www.gravatar.com/avatar/{0}?{1}'.format(
                hashlib.md5(self.user.email.lower()).hexdigest(),
                urllib.urlencode({'d': no_picture, 's': '256'})
                )
                return gravatar_url

          except Exception:
              return no_picture

Answer №2

Utilize a SerializerMethodField for this task.

Add the following code to your serializers file:

# serializers.py

from rest_framework import serializers

class ProfileSerializer(serializers.ModelSerializer):
    get_picture = serializers.SerializerMethodField()

Keep your current code in models.py:

# models.py

class Profile(models.Model):
    ...

    class Meta:
        model = Profile

    def get_picture(self):
        no_picture = 'http://trybootcamp.vitorfs.com/static/img/user.png'
        try:
           filename = settings.MEDIA_ROOT + '/profile_pictures/' +\
               self.user.username + '.jpg'
           picture_url = settings.MEDIA_URL + 'profile_pictures/' +\
               self.user.username + '.jpg'
           if os.path.isfile(filename):
               return picture_url
           else:
               gravatar_url = 'http://www.gravatar.com/avatar/{0}?{1}'.format(
               hashlib.md5(self.user.email.lower()).hexdigest(),
           urllib.urlencode({'d': no_picture, 's': '256'})
           )
               return gravatar_url
        except Exception:
            return no_picture

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with parsing JSON data within PowerShell

While working with JSON, I encountered a specific issue that I need help with. The JSON snippet provided below illustrates the problem: Although I have experimented with various examples of JSON manipulation, most of them focus on simple key/value pairs. ...

What are the challenges of using a shared mutable object?

def check_and_update_dict(d, fields, default_value=None): for field in fields: if not field in d: d[field] = default_value d = { } check_and_update_dict(d, ['cnt1', 'cnt2'], 0) check_and_update_dict(d, ['t ...

Send the output of MPDF back to the browser by utilizing JSON in combination with ExtJS

I am currently using mpdf to generate a PDF report in my PHP code. I have successfully been able to save the PDF file and view it by using Output($pdfFilePath), but now I need to send it back to the browser using JSON without saving it on the server. To ac ...

Using Java's JsonPath library to insert an object into another object

Currently utilizing the JayWay JsonPath library for JSON object manipulation. In need of inserting a JSON object into an existing JSON array: ### before { "students": [] } ### after { "students": [{"id": 1, "name&qu ...

Ajax versus embedding data directly into the HTML code

Currently, my project involves a combination of JavaScript with jQuery and communication with a Django backend. Some aspects of the user interface require Ajax due to the fact that data to be sent is dependent on user input. On the other hand, there is c ...

Manipulate JSON data in a Node.js loop

Currently, I am working on a monitoring system that will indicate on a website whether a server is up or down. I have experimented with various methods such as regex and replacement to modify the JSON file. My main objective is to dynamically change the "s ...

Achieving 5-star ratings on Google through Selenium with Python

I'm attempting to leave a 5-star review for a location on Google Maps. I've successfully written the comment, but I am unable to select the stars. Here is the code snippet I used to submit the comment and give 5 stars: WebDriverWait(driver, 10). ...

Every time I try to loop through my JSON object using an $.each statement, an error is thrown

When I execute an $.each loop on my json object, I encounter an error 'Uncaught TypeError: Cannot read property 'length' of undefined'. It seems that the issue lies within the $.each loop as commenting it out results in the console.log ...

What is the best way to load an ExtJS combobox with a JSON object that includes an array

After retrieving the following JSON from the backend: { "scripts": [ "actions/rss", "actions/db/initDb", "actions/utils/MyFile", "actions/utils/Valid" ], "success": true } The JSON data is stored as follows: t ...

What is the most effective method for locating a specific string within a text file using Python?

Exploring methods to search for a string in a text file using Python, what is the most efficient approach? (considering speed and resource utilization) My initial attempt was as follows. file = open('/home/socfw/src/edl/outbound_monthly.txt') ...

The resize() function in Scikit image raised an error due to an unexpected argument 'anti_aliasing' being passed

I attempted to utilize the resize function with aliasing as outlined in the documentation at from skimage.transform import resize im_test = resize(im_test, (im_test.shape[0] / 3, im_test.shape[1] / 3),anti_aliasing=True) However, this resulted in the fo ...

What could be causing the malfunction of this JavaScript dropdown select feature in Internet Explorer?

I created a website that requires users to input their location, including the city and state. The process involves two dropdown menus: - The first dropdown menu, labeled "state," loads all USA states as selectable options when the website is loaded. This ...

Rendering nested data structures in Django using a tree view

My backend server sends me a JSON response structured as follows: { "compiler": { "type": "GCC", "version": "5.4" }, "cpu": { "architecture": "x86_64", "count": 4 } } I am looking to represent this response ...

Performing a numpy calculation in Python to sum every 3 rows, effectively converting monthly data into quarterly data

I have a series of one-dimensional numpy arrays containing monthly data. My goal is to aggregate these arrays by quarter and create a new array where each element represents the sum of three consecutive elements from the original array. Currently, I am ut ...

enhance typing for variable number of arguments (`args` or `kwargs`)

Displayed below is an example that ensures the IDE type checker or reveal_type correctly identifies the types of k, j, and i. Is there a way to suggest that the typing for args should be an empty tuple, kwargs should be an empty dict, and the return value ...

The dimensions of the matrix are not compatible: In[0]: [47,1000], In[1]: [4096,256]

Recently, I started learning TensorFlow and decided to try image captioning with VGG by following a tutorial. Unfortunately, I encountered an error message: enter image description here Here's the code snippet in question: model = define_model(vocab ...

How can I generate a PDF file directly from byte data in Python without having to write it to a binary file first?

This Python code retrieves data from a database table and converts it into a PDF file without saving it to disk, then displays it in the browser. l_statement = "select srno,attachment from dbo.attachments where srno = 1" sqlcursor.execute(l_stat ...

Is there a way to print a particular value within a matrix using Python, specifically with the help of numpy?

I am facing an issue with a code snippet that is supposed to generate a zero matrix based on a given size (m x n). However, my goal is to extract a specific value from a particular location within that matrix. Despite trying numerous approaches, I have not ...

Convert objects to JSON using ServiceStack serialization with a specific function

I have a C# helper class that defines a JavaScript component with a specific JavaScript function name. new Button({Label = "Execute", OnClick = "ExecuteFunction"}); This will generate a JSON text: { label = "Execute", onClick = ExecuteFunction} (where ...

Tips for extracting data from a webpage that requires clicking the pagination button to load the content

I am currently using Python BeautifulSoup to scrape data from a website. The website has pagination, and everything is working smoothly until I reach page 201. Strangely enough, when I try to access page 201 directly through the URL in the browser, it retu ...