Django:根据日期在页面上显示不同的数据?



是否有一种方法可以根据日期在页面上显示不同的数据?例如,我正在构建一个宏跟踪器,我希望只显示用户输入的当天的数据。因此,他们添加的08-28-2021的餐点只会显示在当天的页面上。

这是我的膳食模型。

class Meal(models.Model):
name = models.CharField(
max_length=1,
choices=TYPES,
default=TYPES[0][0]
)
date = models.DateField()
foods = models.ManyToManyField(Food)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('meal_details', kwargs={'meal_id': self.id})

URL

path('meal/<int:meal_id>/', views.meal_details, name='meal_details')

和视图

@login_required
def meal_details(request, meal_id):
meal = Meal.objects.get(id=meal_id)
unadded_foods = Food.objects.exclude(id__in = meal.foods.all().values_list('id'))
return render(request, 'meals/meal_details.html', {'meal': meal, 'foods': unadded_foods})

这里我们假设您想在模板上显示确切一天的膳食:2021-08-28

import datetime
def meals_list(request):
# If a date is provided to the view then return
# only meals for the given date, else show all meals
year = int(request.GET.get('date_y', None))
month = int(request.GET.get('date_m', None))
day = int(request.GET.get('date_d', None))
if not (date_y and date_m and date_d):
# The date is not provided
meals = Meals.objects.all()
else:
# The date is provided
# Try to retrieve the date_year, date_month, and date_day
# from the given date parameter and ensure you that it is clear
# and correct. After it's just a simple filter operation

meals = Meals.objects.filter(date__date=datetime.date(year, month, day)
return render(request, 'meals/list.html', {'meals': meals, ...})

我再次强调你有责任将一个有效的自定义日期对象传递给你的视图。这里我使用了GET请求。URL示例:/meals?date_y=2021&date_m=08&date_d=28但是你可以使用POST请求或其他方式发送日期到视图

相关内容

  • 没有找到相关文章

最新更新