如何在django';s sqlite数据库?
当我添加一张新卡时,我希望每次都可以选择标题颜色。这是我的代码:如何在django';s sqlite数据库?,django,sqlite,django-models,Django,Sqlite,Django Models,当我添加一张新卡时,我希望每次都可以选择标题颜色。这是我的代码: from django.db import models #Create your models here. class Aziende(models.Model): immagine = models.ImageField() nome = models.CharField(max_length=250) prezzo = models.FloatField() descrizione = mo
from django.db import models
#Create your models here.
class Aziende(models.Model):
immagine = models.ImageField()
nome = models.CharField(max_length=250)
prezzo = models.FloatField()
descrizione = models.CharField(max_length=250)
def __str__(self):
return self.nome
我该怎么办?提前谢谢 将颜色存储为字符域中的十六进制代码:
class Aziende(models.Model):
immagine = models.ImageField()
nome = models.CharField(max_length=250)
prezzo = models.FloatField()
descrizione = models.CharField(max_length=250)
colore = models.CharField(max_length=10, default='#FFFFFF')
def __str__(self):
return self.nome
然后将其显示在模板中:
<h1 class="title" style="color: {{azienda.colore}}" >{{azienda.nome}}</h1>
{{azienda.nome}
我们可以通过两种方式解决此问题:
颜色字段。您可以通过以下方式安装此软件:
pip3 install django-colorfield
接下来,我们可以在您的模型中添加一个颜色字段
:
from colorfield.fields import ColorField
from django.db import models
class Aziende(models.Model):
immagine = models.ImageField()
nome = models.CharField(max_length=250)
prezzo = models.FloatField()
descrizione = models.CharField(max_length=250)
nome_color = ColorField(default='#FF0000')
def __str__(self):
return self.nome
然后,我们可以使用以下内容渲染Aziende
对象的nome
:
{{ aziende_item }}
或者我们可以使用来防止转义名称:
{{ aziende_item.nome|safe }}
{{aziende_item.nome | safe}}
创建另一个应用程序,称其为颜色,另一个模型称其为颜色,然后在当前模型中添加一个外键,如下所示:
from django.db import models
from color.models import Color
#Create your models here.
class Aziende(models.Model):
color = models.ForeignKey(Color, on_delete=models.DO_NOTHING) #Color is your new model
在新的model.py中:
from django.db import models
class Color(models.Model):
color=models.CharField()
def __str__(self):
return self.color
通过这种方式,您可以在以后添加任何颜色,然后可以在添加时随时选择它。您使用的是BorsaConfigcolorfield
(?)而不是ColorField
,因此您在更改模型时可能会出错。是的,幸运的是我解决了这个问题,但现在我得到了一个很小的非彩色文字。我能做什么?非常感谢您的支持@我很乐意帮忙
{{ aziende_item.nome|safe }}
from django.db import models
from color.models import Color
#Create your models here.
class Aziende(models.Model):
color = models.ForeignKey(Color, on_delete=models.DO_NOTHING) #Color is your new model
from django.db import models
class Color(models.Model):
color=models.CharField()
def __str__(self):
return self.color