Reputation: 712
I'm trying to do a very simple thing in Django but getting stuck since I'm a newbie. Basically, on a doctor page in my website, I'm trying to add a field where a user can enter the waiting time for that doctor. For this, I wrote the following model in my models.py:
class WaitingTime(models.Model):
doctor = models.ForeignKey(Doctor)
user = models.OneToOneField(User, unique=True)
time = models.IntegerField("Waiting Time", max_length=2)
After this I wrote the following view:
def WaitingTime(request):
if request.method == 'POST':
form = WaitingTime(request.POST)
if form.is_valid():
doctor = form.cleaned_data['doctor']
user = form.cleaned_data['user']
time = form.cleaned_data['time']
return HttpResponseRedirect('/thanks/')
else:
form = WaitingTime()
This view is the part that I'm most unsure about. Even though I've done 2 tutorials, I feel like a total noob when I have to write this view.
And then, I added this code to my template:
<h4>Please enter the waiting time that you experienced for this doctor.</h4>
<form action="/WaitingTime/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="hidden" name="doctor" value="{{ doctor.name }}" />
<input type="hidden" name="user" value="{{ user.username }}" />
WaitingTime: <input type="text" name="time"><br>
<input type="submit" value="Submit" />
</form>
So basically, I'm having trouble adding data from the front end to my database, something very trivial and basic. I already ran python manage.py syncdb and checked using the SQLite Database Browser. The table with the appropriate columns has been added. Please help. Thanks a lot in advance.
Upvotes: 0
Views: 172
Reputation: 12613
In order to make changes to the database your views needs to be changed to -
def WaitingTime(request):
if request.method == 'POST':
form = WaitingTimeForm(request.POST) #class specified in forms.py
if form.is_valid():
doctor = form.cleaned_data['doctor']
user = form.cleaned_data['user']
time = form.cleaned_data['time']
WaitingTimeObject = WaitingTime(doctor=doctor, user=user, time=time)
WaitingTimeObject.save()
return HttpResponseRedirect('/thanks/')
Upvotes: 4