I’m trying to set the default value in the form (the field is the date for publishing the article “public”), but when loading the form on the page, the field is empty. I tried to set the default value in the "header" field (any value, not necessarily today's date) - also does not appear.
form:
from main.models import Article
from datetime import datetime
class AddArticleForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AddArticleForm, self).__init__(*args, **kwargs)
self.fields['publish'].initial = datetime.now()
class Meta:
model = Article
fields = ('title', 'author', 'body', 'publish', 'status')
labels = {
'body': 'Text'
}
widgets = {
'title': forms.TextInput(attrs={'class': 'md-form'}),
'author': forms.TextInput(attrs={'class': 'md-form'}),
'body': forms.Textarea(attrs={'class': 'md-textarea', 'rows': 3}),
'publish': forms.DateTimeInput(attrs={'class': 'md-form'}),
'status': forms.Select(attrs={'class': 'custom-select'})
}
views:
def add_article(request):
form = AddArticleForm(request.POST)
if form.is_valid():
form.save()
return redirect('/articles/')
args = {
'form': form
}
return render(request, 'html/add_article.html', args)
html:
...
<form action="." method="post" class="add-article">
{% csrf_token %}
{% for field in form %}
<div class="md-form">
{% if field.name != 'status' and field.name != 'publish' %}
<label for="{{ field.name }}">{{ field.label }}</label> {{ field }}
{% else %}
<label for="{{ field.name }}"></label> {{ field }}
{% endif %}
</div>
{% endfor %}
<button type="submit" class="btn btn-pink btn-block">Share</button>
</form>
...