我的models.py有一个像这样的日期字段
class Topic(models.Model):
text = models.CharField(max_length=200)
date_added = models.DateTimeField('date published')
def __str__(self):
return self.text
像这样的View.py:
def new_topic(request):
if request.method != 'POST':
form = TopicForm()
else:
form = TopicForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('blog:topics'))
context = {'form' : form}
return render(request, 'blog/new_topic.html', context)
form.py:
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['text', 'date_added']
labels = {'text': ''}
现在的问题是我需要自动向该字段添加日期。要有任何数据库输入。
答案 0 :(得分:2)
在字段定义中使用auto_now_add
:
date_added = models.DateTimeField('date published', auto_now_add=True)