Django Datetime Choice 字段问题
Django Datetime Choice field issue
所以,我对 Django 很陌生,我正在尝试将以下想法付诸实践:
在我的对象创建表单中,我希望用户填写日期字段以便在对象上放置各种时间戳。问题是我只想让两天可供选择——今天和明天。我不想使用 DateTime 字段并让用户手动输入日期,因为它看起来很丑而且使用起来不太方便。我决定尝试实现一个选择字段。它呈现得很好,但到目前为止我还没有弄清楚如何使我的表单数据通过有效。我仔细研究了 pdb,结果阅读了 cleaning/validating 方法,但我仍然不知道如何让它工作。
我已经尝试过的:
添加函数 return 今天和明天作为日期对象和字符串(这里是后者)
错误文本是:
select 一个有效的选择,不是可用的选择之一
我认为它在 clean() 方法期间以某种方式失败。
或者,如果这不是一个合理的想法(它可能不是),那么可能有什么替代方案?
models.py:
def get_today():
return datetime.date.strftime( datetime.datetime.now().date(), format="%Y-%m-%d")
def get_tomorrow():
return datetime.date.strftime(((datetime.datetime.now() + datetime.timedelta(days=1)).date()), format="%Y-%m-%d")
class User(AbstractUser):
slug = models.SlugField(max_length=100, unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.username)
super(User, self).save(*args, **kwargs)
class Task(models.Model):
TODAY = get_today
TOMORROW = get_tomorrow
DATE_SELECTION = (
(TODAY, "Today"),
(TOMORROW, "Tomorrow"),
)
task_title = models.CharField(verbose_name="Название задачи: ", max_length=150)
task_description = models.TextField(verbose_name="Описание: ", max_length=1000)
task_user = models.ForeignKey('User', on_delete=models.CASCADE)
task_date = models.DateField(choices=DATE_SELECTION)
def __str__(self):
return self.task_title
我用来处理表单的 views.py 基于 class 的视图:
class CreateTask(CreateView):
model = Task
form_class = TaskForm
success_url = '/{user}'
def get(self, request, *args, **kwargs):
form = TaskForm()
return render(request, 'create_task.html', {'form': form})
def post(self, request, *args, **kwargs):
form = TaskForm(request.POST)
if form.is_valid():
task = form.save(commit=False)
task = Task(**form.cleaned_data)
task.task_user = request.user
task.save()
messages.add_message(request, messages.INFO, "Task %s was successfully created!" % task.task_title)
return redirect('tasks:user_home', user=request.user)
else:
return render(request, 'create_task.html', {'form': form, 'errors':form.errors})
forms.py
class TaskForm(forms.ModelForm):
task_date=forms.DateField(input_formats="%Y-%m-%d")
class Meta:
model = Task
fields = ['task_title', 'task_description']
更新:
经过大量实验和研究,我创建了以下解决方案:
models.py
class Task(models.Model):
task_title = models.CharField(verbose_name="Название задачи: ", max_length=150)
task_description = models.TextField(verbose_name="Описание: ", max_length=1000)
task_user = models.ForeignKey('User', on_delete=models.CASCADE)
task_date = models.DateField()
def __str__(self):
return self.task_title
(^^^注意缺少select离子场)
和 forms.py:
def get_today():
return datetime.datetime.now().date()
def get_tomorrow():
return (datetime.datetime.now() + datetime.timedelta(days=1)).date()
TODAY = get_today
TOMORROW = get_tomorrow
DATE_SELECTION = (
(TODAY, "Today"),
(TOMORROW, "Tomorrow"),
)
class TaskForm(forms.ModelForm):
task_date = forms.DateField(input_formats=["%Y-%m-%d"], widget=forms.Select(choices=DATE_SELECTION))
class Meta:
model = Task
fields = ['task_title', 'task_description']
(^^^注意 select 小部件,input_formats,它必须始终是一个列表)
更新:经过大量实验和研究,我创建了以下解决方案:
models.py
class Task(models.Model):
task_title = models.CharField(verbose_name="Название задачи: ", max_length=150)
task_description = models.TextField(verbose_name="Описание: ", max_length=1000)
task_user = models.ForeignKey('User', on_delete=models.CASCADE)
task_date = models.DateField()
def __str__(self):
return self.task_title
(^^^注意缺少select离子场)和forms.py:
def get_today():
return datetime.datetime.now().date()
def get_tomorrow():
return (datetime.datetime.now() + datetime.timedelta(days=1)).date()
TODAY = get_today
TOMORROW = get_tomorrow
DATE_SELECTION = (
(TODAY, "Today"),
(TOMORROW, "Tomorrow"),
)
class TaskForm(forms.ModelForm):
task_date = forms.DateField(input_formats=["%Y-%m-%d"], widget=forms.Select(choices=DATE_SELECTION))
class Meta:
model = Task
fields = ['task_title', 'task_description']
(^^^注意 select 小部件,input_formats,它必须始终是一个列表)
所以,我对 Django 很陌生,我正在尝试将以下想法付诸实践: 在我的对象创建表单中,我希望用户填写日期字段以便在对象上放置各种时间戳。问题是我只想让两天可供选择——今天和明天。我不想使用 DateTime 字段并让用户手动输入日期,因为它看起来很丑而且使用起来不太方便。我决定尝试实现一个选择字段。它呈现得很好,但到目前为止我还没有弄清楚如何使我的表单数据通过有效。我仔细研究了 pdb,结果阅读了 cleaning/validating 方法,但我仍然不知道如何让它工作。 我已经尝试过的: 添加函数 return 今天和明天作为日期对象和字符串(这里是后者) 错误文本是: select 一个有效的选择,不是可用的选择之一 我认为它在 clean() 方法期间以某种方式失败。 或者,如果这不是一个合理的想法(它可能不是),那么可能有什么替代方案?
models.py:
def get_today():
return datetime.date.strftime( datetime.datetime.now().date(), format="%Y-%m-%d")
def get_tomorrow():
return datetime.date.strftime(((datetime.datetime.now() + datetime.timedelta(days=1)).date()), format="%Y-%m-%d")
class User(AbstractUser):
slug = models.SlugField(max_length=100, unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.username)
super(User, self).save(*args, **kwargs)
class Task(models.Model):
TODAY = get_today
TOMORROW = get_tomorrow
DATE_SELECTION = (
(TODAY, "Today"),
(TOMORROW, "Tomorrow"),
)
task_title = models.CharField(verbose_name="Название задачи: ", max_length=150)
task_description = models.TextField(verbose_name="Описание: ", max_length=1000)
task_user = models.ForeignKey('User', on_delete=models.CASCADE)
task_date = models.DateField(choices=DATE_SELECTION)
def __str__(self):
return self.task_title
我用来处理表单的 views.py 基于 class 的视图:
class CreateTask(CreateView):
model = Task
form_class = TaskForm
success_url = '/{user}'
def get(self, request, *args, **kwargs):
form = TaskForm()
return render(request, 'create_task.html', {'form': form})
def post(self, request, *args, **kwargs):
form = TaskForm(request.POST)
if form.is_valid():
task = form.save(commit=False)
task = Task(**form.cleaned_data)
task.task_user = request.user
task.save()
messages.add_message(request, messages.INFO, "Task %s was successfully created!" % task.task_title)
return redirect('tasks:user_home', user=request.user)
else:
return render(request, 'create_task.html', {'form': form, 'errors':form.errors})
forms.py
class TaskForm(forms.ModelForm):
task_date=forms.DateField(input_formats="%Y-%m-%d")
class Meta:
model = Task
fields = ['task_title', 'task_description']
更新: 经过大量实验和研究,我创建了以下解决方案:
models.py
class Task(models.Model):
task_title = models.CharField(verbose_name="Название задачи: ", max_length=150)
task_description = models.TextField(verbose_name="Описание: ", max_length=1000)
task_user = models.ForeignKey('User', on_delete=models.CASCADE)
task_date = models.DateField()
def __str__(self):
return self.task_title
(^^^注意缺少select离子场) 和 forms.py:
def get_today():
return datetime.datetime.now().date()
def get_tomorrow():
return (datetime.datetime.now() + datetime.timedelta(days=1)).date()
TODAY = get_today
TOMORROW = get_tomorrow
DATE_SELECTION = (
(TODAY, "Today"),
(TOMORROW, "Tomorrow"),
)
class TaskForm(forms.ModelForm):
task_date = forms.DateField(input_formats=["%Y-%m-%d"], widget=forms.Select(choices=DATE_SELECTION))
class Meta:
model = Task
fields = ['task_title', 'task_description']
(^^^注意 select 小部件,input_formats,它必须始终是一个列表)
更新:经过大量实验和研究,我创建了以下解决方案:
models.py
class Task(models.Model):
task_title = models.CharField(verbose_name="Название задачи: ", max_length=150)
task_description = models.TextField(verbose_name="Описание: ", max_length=1000)
task_user = models.ForeignKey('User', on_delete=models.CASCADE)
task_date = models.DateField()
def __str__(self):
return self.task_title
(^^^注意缺少select离子场)和forms.py:
def get_today():
return datetime.datetime.now().date()
def get_tomorrow():
return (datetime.datetime.now() + datetime.timedelta(days=1)).date()
TODAY = get_today
TOMORROW = get_tomorrow
DATE_SELECTION = (
(TODAY, "Today"),
(TOMORROW, "Tomorrow"),
)
class TaskForm(forms.ModelForm):
task_date = forms.DateField(input_formats=["%Y-%m-%d"], widget=forms.Select(choices=DATE_SELECTION))
class Meta:
model = Task
fields = ['task_title', 'task_description']
(^^^注意 select 小部件,input_formats,它必须始终是一个列表)