gpt4 book ai didi

python - 如何在 Django 中存储前导零

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:26 25 4
gpt4 key购买 nike

我目前正在为我的网站制作一个查看计数器,我将让它支持 0 到 9999 之间的任何计数。我还希望查看计数始终显示前导零,所以如果有 8 次查看它会显示为 0008。我遇到的问题是我的模型会自动删除所有前导零,我不知道如何删除它。如果有人能帮助我,那就太好了,如果数字存储为 0008,我认为我的 +1 方法是否仍然有效?干杯!

查看 -

def listing(request, pk):

job_listing = JobListing.objects.get(pk=pk)

def view_counter():
view_count = job_listing.listing_view_counter
job_listing.listing_view_counter = view_count + 1
job_listing.save()

view_counter()

context_dict = {'joblistings': job_listing}

return render(request, 'listing.html', context_dict)

模型 -

class JobListing(models.Model):

region_choice = (
('Auckland', 'Auckland'),
('Wellington', 'Wellington'),
('Christchurch', 'Christchurch')
)
industry_choice = (
('Accounting', 'Accounting'),
('Agriculture, fishing & forestry', 'Agriculture, fishing & forestry'),
('Automotive', 'Automotive'),
('Banking, finance & insurance', 'Banking, finance & insurance'),
('Construction & Architecture', 'Construction & Architecture'),
('Customer service', 'Customer service'),
)
employment_type_choice = (
('Full Time', 'Full Time'),
('Part Time', 'Part Time'),
('One-off', 'One-off'),
('Other', 'Other')
)

user = models.CharField(max_length=50)
job_title = models.CharField(max_length=30)
pay_rate = models.DecimalField(max_digits=10, decimal_places=2)
employment_type = models.CharField(max_length=10, choices=employment_type_choice)
job_description = models.CharField(max_length=2000)
business_address_region = models.CharField(max_length=50, choices=region_choice)
business_address_suburb = models.CharField(max_length=50)
business_industry = models.CharField(max_length=50, choices=industry_choice)
email = models.EmailField(max_length=50, blank=True, null="True")
telephone = models.IntegerField(blank=True, null='True')
listing_view_counter = models.IntegerField(default=0)
active_listing = models.BooleanField(default=True)

class Meta:
verbose_name = 'Job Listing'

def clean(self):
if not (self.email or self.telep

hone):
raise ValidationError("You must specify either email or telephone")
if not self.email:
self.email = "Not Provided"

def __unicode__(self):
return "%s" % self.job_title

最佳答案

您可以使用 stringformat模板过滤器将填充应用于模板内的数字。

例如:

{{ job_listing.listing_view_counter|stringformat:"04d" }}

关于python - 如何在 Django 中存储前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34866575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com