Though the datalist displays the list of values, upon selection from the form the value is not getting stored/assigned to the field which in turn not getting saved to the DB. Below are the setup. Request help on the same. - Thank you!
The field ‘State’ is linked with list of values from the model ‘State’ which though displays the list of values, upon selection and submitting the form the value disappears and error throws upon.
Portion of html file:
<tr>
<th>{{ form.State.label_tag }}</th>
<td>
{{ form.State.errors }}
<!--{{ form.State }}-->
<input autoComplete="on" type="text" list="States" placeholder="State" class="form-control" />
<datalist id="States">
{% for s in StateList %}
<option value="{{ s.StateName }}"></option>
{% endfor %}
</datalist>
</td>
</tr>
related view in views.py,
def create(request):
form = EmployeeMForm()
StateList = State.objects.all()
if request.method == 'POST':
form = EmployeeMForm(request.POST)
if form.is_valid():
form.save()
return redirect('employeem-list')
context = {
'StateList': StateList,
'form': form,
}
return render(request,'EmployeeM/create1.html', context)
respective models:
class State(models.Model):
StateCode = models.CharField(max_length=2)
StateTIN = models.IntegerField()
StateName = models.CharField(max_length=100)
def __str__(self):
return self.StateName
class EmployeeM(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
Name = models.CharField(max_length=200)
Email = models.EmailField()
Contact = models.CharField(max_length=20)
Role = models.CharField(max_length=200)
Salary = models.IntegerField()
State = models.ForeignKey(State,on_delete=models.SET_NULL,null=True)
JoinDate = models.DateField()
ToDate = models.DateField()
def __str__(self):
return self.Name
respective forms.py
class EmployeeMForm(forms.ModelForm):
class Meta:
model = EmployeeM
fields = ('Name', 'Email', 'Contact', 'Role', 'Salary', 'State', 'JoinDate', 'ToDate')
labels = {
'JoinDate':'Join Date',
'ToDate':'Last Date',
}
widgets = {
'Name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Name', 'style': 'width: 400px', 'style': 'height: 30px'}),
'Email': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Email', 'style': 'width: 400px'}),
'Contact': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Contact No.', 'style': 'width: 400px'}),
'Role': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Role', 'style': 'width: 400px'}),
'Salary': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Salary', 'style': 'width: 400px'}),
'State': forms.Select(attrs={'class': 'form-control', 'placeholder': 'State', 'style': 'width: 400px'}),
'JoinDate': forms.DateInput(attrs={'type':'date', 'class': 'form-control', 'placeholder': 'Join date', 'style': 'width: 400px'}),
'ToDate': forms.DateInput(attrs={'type':'date', 'class': 'form-control', 'placeholder': 'Last date', 'style': 'width: 400px'}),
}