display field choice as part of a string

Date: March 29th 2016
Last updated: March 29th 2016

When I refer to field choice I am talking about a predefined choice list given in models.py. For example consider the following model. When an instance of this model is called, the output will return the waves name and the break choice. However, the break choice will return either 'PB' or 'BB' rather than 'Point break' or 'beach break'. This can be fixed by asking for the display name using django's built-in get method.

models.py

class Wave(models.Model):
    # break choice
    POINTBREAK = 'PB'
    BEACHBREAK = 'BB'
    # create tuples containing selection and label
    WAVECHOICE = ((POINTBREAK, 'Point break'),(BEACHBREAK, 'Beach break'),)
    wavebreak = models.CharField(max_length=2, choices=WAVECHOICE, default=BEACHBREAK)
    wavename = models.CharField(max_length=40)

    def __str__(self):
        return '{} ({} at {})'.format(self.wavename, self.wavebreak)

Update to models.py

class Wave(models.Model):
    # <- snipped: same as above ->    
    def __str__(self):
        return '{} ({} at {})'.format(self.wavename,
                               ###### solution #############
                               self.get_wavebreak_display())
                               #############################

Another option: modify views.py

The get method can be used in views.py as well. In this example I am requesting the display name instead of the database value to pass to my html template. The objective of this example is to render on the webpage a subset of information showing the boards that a surfer has selected. It should be noted that the two models considered here (Surfer and Board) have a Many to Many relationship.

models.py

class Board(models.Model):
    #<- snipped ->
    SQUASH = 'SQH'
    SQUARE = 'SQE'
    ROUNDEDSQU = 'RSQ'
    TAIL = ((SQUASH, 'Squash Tail'),
            (SQUARE, 'Square Tail'),
            (ROUNDEDSQU, 'Rounded Square Tail'),)
    boardtail = models.CharField('Tail shape',max_length=3, choices=TAIL)

class Surfer(models.Model):
    #<- snipped ->
    boards = models.ManyToManyField(Board)

views.py

from .models import Surfer, Board

@login_required
def profilepage(request, surfer_id):
    surfer_profile = dict()
    surfer = get_object_or_404(Surfer, pk=surfer_id)
    #<- snipped ->

    # create an empty list 
    # (This will get appended to the empty dictionary later)
    boards = []

    # loop over boards list (access to the many to many relationship)
    for board in surfer.boards.values_list():

        # Access the Board model using the primary key of each board
        eachboard = get_object_or_404(Board, pk=board[0])

        ################# Solution ####################
        tailshape = eachboard.get_boardtail_display()
        ###############################################

        # create info string 
        boardstring = '{} {} ({} {} {})'.format(board[4], board[11],
                                                board[5], board[6],
                                                tailshape)
        boards.append(boardstring)
    surfer_profile['boards'] = boards #(', '.join(boards))


    return render(request, 'surferprofile/profile.html',
                    {'surfer': surfer_profile})

profile.html

<div>
  {% for board in surfer.boards %}
    <p>{{ board }}</p>
  {% endfor %}
</div>

http://127.0.0.1:8080/1/ (profile page for user=1)
Note that I have snipped the html above and I have not shown the CSS stylesheet to produce the following image. Note in the image below the display name ("Rounded Square Tail") rather than the database value ("RSQ").

Another option: modify html template

The get method can also be used in an html template. However, the method is called without brackets. Here is a snipped section of the html template for a row entry in a table. This provides the display name (in this case: "offshore") rather than the database field which is "OF".

<td id='diarytableentry'>{{ entry.get_winddir_display }}</td>

results matching ""

    No results matching ""