Reputation: 145
I am building a basic form through which data can be entered into django model database. Everything works fine except the choicefield which does not post value to the database.I want the user to select from 'Morning' and 'Evening' (default value should be blank) which can then be posted to 'time' model.
Following is my models.py:
date = models.DateTimeField(auto_now_add=True, null=True)
time = models.CharField(max_length=200, null=True, blank=True)
cow1 = models.FloatField(null=True, blank=True)
cow2 = models.FloatField(null=True, blank=True)
cow3 = models.FloatField(null=True, blank=True)
cow4 = models.FloatField(null=True, blank=True)
Views.py:
def home(request):
if request.method=="POST":
cow1 = request.POST.get("cow1", False)
cow2 = request.POST.get("cow2", False)
cow3 = request.POST.get("cow3", False)
cow4 = request.POST.get("cow4", False)
time = request.POST.get("time", False)
ins = models.cow(cow1=cow1, cow2=cow2, cow3=cow3, cow4=cow4, time=time)
ins.save()
return render(request, 'dataentry/home.html')
And home.html:
<form action = "" method = "POST">
{% csrf_token %}
<label for="cow1">cow1</label>
<input id="cow1" type="number" name="cow1">
<label for="cow2">cow2</label>
<input id="cow2" type="number" name="cow2">
<label for="cow3">cow3</label>
<input id="cow3" type="number" name="cow3">
<label for="cow4">cow4</label>
<input id="cow4" type="number" name="cow4">
<label for="time">Time</label>
<select form="time" name="time" id="time">
<option value="time">Morning</option>
<option value="time">Evening</option>
</select>
<input type="submit" value="OK">
</form>
Little help will be appreciated. THANKS!
Upvotes: 0
Views: 353
Reputation: 550
you have to change the value option to Morning and Evening.
The name attribute in select is the key.
The value attribute in option is the value
Your code returns "time":"time"
with this :
<select name="time" id="time">
<option value="none" selected disabled hidden>
Select an Option
</option>
<option value="Morning">Morning</option>
<option value="Evening">Evening</option>
</select>
It will return "time":"Morning" or "time":"Evening"
I delete the form attribute in select tag because there is no need to do that in your case.
But if you want to keep it, you can add id= "time" in your <form action = "" method = "POST">
You should consider to use ModelForm (a real timesaver)
Upvotes: 1