我在Django中遇到一些DateTime问题。我认为这全都归结为数据类型和转换,我只是不太了解。如果有人可以清理我的代码,我将不胜感激,如下所述。我也要求不要改变太多。我对编程非常陌生。我敢肯定,有更好的方法可以完成我想做的事情,但是我的理解仅限于以某种方式做事。因此,如果您可以不做大量更改就可以帮助我完成这项工作,我将不胜感激。
好吧...
作为一个学习项目,我正在Django(Python 2,Django 1)中构建一个非常基本的“ Travel App”。我希望用户能够输入旅行的开始日期和结束日期。开始日期必须在将来,结束日期必须在开始日期之后。
首先,我在模型中创建Trip表:
class Trip(models.Model):
destination = models.CharField(max_length=55)
description = models.TextField()
start_date = models.DateField(null=True)
end_date = models.DateField(null=True)
travelers = models.ManyToManyField(User, related_name="trips")
planned_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="trips_added")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = TripManager()
我认为一切都很好。
在模型中,我还为“添加行程”表单设置了验证和添加方法。这是我目前的情况-我知道这里有些错误:
class TripManager(models.Manager):
def trip_validation(self, postData):
start_date = datetime.strptime(postData['start_date'], "%Y-%m-%d")
end_date = datetime.strptime(postData['end_date'], "%Y-%m-%d")
errors = {}
if len(postData['destination']) < 1:
errors['destination'] = 'You must enter trip destination.'
if len(postData['description']) < 1:
errors['description'] = 'You must enter trip description.'
if len(postData['start_date']) < 1:
errors['start_date'] = 'Please enter a start date for your trip.'
elif not start_date > timezone.now():
errors['start_date'] = 'Your trip start date must be in the future.'
if len(postData['end_date']) < 1:
errors['end_date'] = 'Please enter an end date for your trip.'
elif not self.end_date > self.start_date:
errors['end_date'] = 'Trip end date must be after start date.'
return errors
def trip_add(self, postData, user_id):
destination = postData['destination']
description = postData['description']
start_date = datetime.strptime(postData['start_date'], "%Y-%m-%d")
end_date = datetime.strptime(postData['end_date'], "%Y-%m-%d")
user_obj = User.objects.get(id=user_id)
return self.create(destination=postData['destination'], description=postData['description'], start_date=postData['start_date'], end_date=postData['end_date'], planned_by=user_obj)
现在,当我运行该应用程序时,我无法验证用户是否输入了日期-我得到了time data '' does not match format '%Y-%m-%d'
。因此,这是第一个障碍,但是我怀疑一旦掌握了这一点,其余的代码就会更容易排成一行。
我没有在视图中包括我做的事情,即所谓的trip_validation和trip_add方法,将错误放入上下文字典等,因为我认为这是可以的(或者至少Django尚未对此抱怨,因为它无法到达那里!)。
谢谢。
更新
我被要求发布视图和完整的追溯,所以来了...
视图中的add_trip方法:
def add_trip(request):
if request.method == "POST":
errors = Trip.objects.trip_validation(request.POST)
if not errors:
trip = Trip.objects.trip_add(request.POST, request.session['uid'])
# redirect to individual trip page
return render(request, 'html_files/add.html')
else:
context = {
'errors' : errors
}
return render(request, 'html_files/add.html', context=context)
elif request.method == "GET":
first_name = User.objects.get(id=request.session['uid']).first_name
context = {
'first_name' : first_name,
}
return render(request, 'html_files/add.html', context=context)
当前,我只是想通过空的“开始日期”字段提交表单,希望通过上下文命令看到错误,即“请输入旅行的开始日期”。我还没有深入研究代码。
跟踪:
File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner
39. response = get_response(request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/gbroesche/Desktop/TravelBuddy/apps/trips/views.py" in add_trip
22. errors = Trip.objects.trip_validation(request.POST)
File "/Users/gbroesche/Desktop/TravelBuddy/apps/trips/models.py" in trip_validation
15. start_date = datetime.strptime(postData['start_date'], "%Y-%m-%d")
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py" in _strptime
325. (data_string, format))
Exception Type: ValueError at /trips/add/
Exception Value: time data '' does not match format '%Y-%m-%d'