Skip to main content
 首页 » 编程设计

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

2025年05月04日9powertoolsteam

我目前正在为我的网站制作一个查看计数器,我将让它支持 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" }}