i am trying to save data from HTML input into MySql database using Django. Other forms that i created work. My conclusion is that it doesn't work because of time input. I have it converted into datettime python type which should make it work but it still doesn't save. Would you please check my code and see what can be possible the reason for it not saving?
views.py file:
def employee_view(request):
table = employeeModel.objects.all()
context = {"table": table}
if request.method == "POST":
postCopy = request.POST.copy() # to make it mutable
postCopy['barberStartTime'] = datetime.strptime('15/05/22 ' postCopy['barberStartTime'], '%d/%m/%y %H:%M').time()
postCopy['barberEndTime'] = datetime.strptime('15/05/22 ' postCopy['barberEndTime'], '%d/%m/%y %H:%M').time()
request.POST = postCopy
form = employeeForm(request.POST or NONE)
if form.is_valid():
form.save()
return render(request, 'accounts/employee.html', context)
return render(request, 'accounts/employee.html', context)
python employeeModel:
class employeeModel(models.Model):
barberName = models.CharField(max_length=50)
barber_workplace = models.ForeignKey(workplacesModel, on_delete=models.CASCADE)
barberStartTime = models.TimeField()
barberEndTime = models.TimeField()
class barbers:
db_table = "home_employeemodel"
python employeeForm:
class employeeForm(forms.ModelForm):
barberStartTime = forms.TimeField(widget=forms.TimeInput(format='%H:%M:%S'))
barberEndTime = forms.TimeField(widget=forms.TimeInput(format='%H:%M:%S'))
class Meta:
model = employeeModel
fields = ["barberName", "barber_workplace", "barberStartTime", "barberEndTime"]
html input form: (it is part of a table - reason for tr/td tags):
<tr>
<form method="POST">{% csrf_token %}
<td scope="row">---</td>
<td ><input type="text" name="barberName" placeholder="Meno"/></td>
<td ><input type="number" name="barberWorkplace" placeholder="Mesto"/></td>
<td ><input type="time" name="barberStartTime"/></td>
<td ><input type="time" name="barberEndTime"/></td>
<td><button >Pridať</button></td>
<form>
</tr>
CodePudding user response:
So i finally figured out where the mistake was. The problem was incorrectly named input for barber workplace. It was named barberWorkplace while it should have been named barber_workplace.