Answer the question
In order to leave comments, you need to log in
How can I make the value itself be written to the database when a new row is created?
How can I make the value itself be written to the database when a new row is created?
I have a form where the user can enter values for 4 fields out of 5. The fifth field is a date and time field. How can I make it so that the date and time is automatically written to this db row when this row is added?
html:
<form method='post' id='adding_text'>
{% csrf_token %}
{{ form.author }}<br>
{{ form.title }}<br>
{{ form.topic }}<br>
{{ form.text }}<br>
{{ form.date_and_time }}<br>
<button type='submit' id='submit_button_in_adding_text_form'>Добавить</button>
</form>
from .models import Texts
from django import forms
from django.forms import ModelForm
class TextsForm(ModelForm):
class Meta:
model = Texts
fields = ['author', 'title', 'topic', 'text', 'date_and_time']
widgets = {
'author': forms.TextInput(attrs={
'class': 'input_author input_in_adding_text',
'placeholder': 'Текст',
'readonly': 'readonly'
}),
'title': forms.TextInput(attrs={
'class': 'input_title input_in_adding_text',
'placeholder': 'Название текста'
}),
'topic': forms.TextInput(attrs={
'class': 'input_topic input_in_adding_text',
'placeholder': 'Тема текста',
}),
'text': forms.Textarea(attrs={
'class': 'input_text input_in_adding_text',
'placeholder': 'Текст'
}),
'date_and_time': forms.DateTimeInput(attrs={
'class': 'input_date_and_time input_in_adding_text',
'placeholder': 'Дата и время',
'readonly': 'readonly'
}),
}
class Texts(models.Model):
author = models.CharField('Автор', max_length=50, default='Аноним')
title = models.CharField('Название', max_length=100)
topic = models.CharField('Тема', max_length=100, default='')
text = models.TextField('Текст')
date_and_time = models.DateTimeField('Дата и время')
def __str__(self):
return self.title
class Meta:
verbose_name = 'Текст'
verbose_name_plural = 'Тексты'
def adding_text(request):
error = ''
if request.method == 'POST':
form = TextsForm(request.POST)
if form.is_valid():
form.save()
else:
error = 'Форма была заполнена неверно, повторите ввод'
return redirect('texts')
form = TextsForm()
data = {
'form': form
}
return render(request, 'adding_text.html', data)
Answer the question
In order to leave comments, you need to log in
I figured this works great:
date_and_time = models.DateTimeField(default=timezone.now)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question