如何在Django中存储Zero Zero

时间:2016-01-19 00:31:07

标签: python django

我目前正在为我的网站制作一个视图计数器,我将支持从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

3 个答案:

答案 0 :(得分:5)

你自己太难了。将数据存储在代码中(作为数字),并在模板中添加0填充。

https://www.djangosnippets.org/snippets/543/

执行此操作的一些代码示例。

答案 1 :(得分:3)

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

例如:

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

答案 2 :(得分:1)

并非真正存储前导零,但您可以将property添加到JobListing模型中。

@property
def view_counter_display(self):
    return str(self.listing_view_counter).zfill(4)

然后,您可以在模板中将其作为{{ obj.view_counter_display }}

进行访问

或者只使用内置的stringformat过滤器。

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