在我的一个django中,我有一个在数据库中创建新产品的表单:
在视图.py在
class ProductCreateView(LoginRequiredMixin, CreateView):
template_name = "products/my-products.html"
model = Product
form_class = AddNewProductForm
def form_valid(self, form):
obj = form.save(commit=False)
obj.user = self.request.user
obj.save()
return HttpResponseRedirect("/my-products/")
在表单.py在
^{pr2}$使用上述方法,一切都能完美地工作。在
我想将当前日期和时间添加到日期和时间小部件中,因此我尝试了以下操作:
在表单.py在
class AddNewProductForm(forms.ModelForm):
date = forms.DateField(label='date', initial=datetime.date.today(),
widget=forms.SelectDateWidget(years=AVAILABLE_YEAR_CHOICES))
time = forms.TimeField(label="time", initial=datetime.datetime.now().strftime("%H:%M"))
class Meta:
model = Product
fields = ["title", "desrciption"]
当我使用这个时,我得到一个错误,日期字段是None。在
我不知道为什么会这样。只使用Meta-works中的字段,但做一些自定义操作却没有任何效果。在
您可以使用
get_initial_for_field
方法也不是
datetime.datetime.now().strftime("%H:%M")
做下一步datetime.datetime.now().time()
您还需要指定第二个示例中的字段:
相关问题 更多 >
编程相关推荐