0

I am confused on how to implement a Django model with the value being a special html character code for making a chessboard. As a reference I'm looking at a sudoku board model:

class Board(models.Model):
    name = models.CharField(max_length=4, primary_key=True)
    value = models.SmallIntegerField()

The value for sudoku is easy, since the table will only be filled with numbers. For reference here's a snippet from the sudoku page_data dictionary in views.py giving each table cell its appropriate value:

{"r1c1": 6, "r1c2": 7, "r1c3": 0, ...}

I don't know what to put for my model's value variable:

class Board(models.Model):
    name = models.CharField(max_length=2, primary_key=True)
    value = 

Here's a snippet of where I assign the name/value pairs in my views.py with the special HTML chess piece character codes in my own page_data dictionary:

{"a8": html.unescape('♖'), "b8": html.unescape('♘'), "c8": html.unescape('♗'), ...}

Any help is appreciated.

1 Answers1

0

So you are looking for a way to store your json data in a django model field.

One option would be to convert your json data to a string and store it in a Charfield.

class Board(models.Model):
    name = models.CharField(max_length=4, primary_key=True)
    value = models.CharField(blank=True, null=True)

Then convert your json data to a string with the following code:

import json

data = {"r1c1": 6, "r1c2": 7, "r1c3": 0}
Board.objects.create(name="bo", value=json.dumps(data))

You can use the json data in the template by using the safe tag:

from django.utils.safestring import SafeString

def view(request):
    return render(request, 'template.html', {'board': SafeString(my_board.value)})

If you do not want to convert your json to string, you can take a look at the JSONField.

Helge Schneider
  • 483
  • 5
  • 8