0

Hi i am relatively new to Django. I am currently trying to store values into database. Timesheet.html is basically my form and i have tried to do the validation but it doesn't work. I have searched everything i can but the data being filled out wont be saved into database. Is there anywhere to check that the checkbox has been ticked before user can submit it ?

timesheet.html

<form method="POST" onsubmit="return validation()" action="">
    {% csrf_token %}
    <div class="content-wrapper">
        <div class="sub-content">
            <div>
                <p>Student ID: {{timesheet.studentID}}</p>
                <input id="sid" type="field" name="studentid">
            </div>
        </div>

        <div class="sub-content">
            <div>
                <p>Student Name: {{timesheet.studentName}}</p>
                <input id="sname" type="field" name="studentname">
            </div>
        </div>

        <div class="sub-content">
            <div>
                <p>Start Date: {{timesheet.startDate}}</p>
                <input id="sdate" type="date" name="startdate">
            </div>
        </div>

        <div class="sub-content">
            <div>
                <p>End Date: {{timesheet.endDate}}</p>
                <input id="edate" type="date" name="enddate">
            </div>
        </div>
    </div>
    <div class="end-content">
        <div class="center-align">
            <div class="checklist">
                <p>By checking this box I agree that I have satisfied all requirements to continue receiving my scholarship
            allowance.</p>
                <input id="agree" type="checkbox" name="checkbox" class="tick-att">
            </div>
            <br>
            <div class="align-right">
                <input type="submit" class="button" name="submit" value="submit" >
            </div>
      </div>
    </div>
</form>

models.py

class Timesheet(models.Model):
    studentID = models.CharField("Student ID", max_length=8, primary_key=True, default="")
    studentName = models.CharField("Student Name", max_length=500, default="")
    startDate = models.DateField("Start Date", max_length=8)
    endDate = models.DateField("End Date", max_length=8)

    def __str__(self):
        return self.studentID

class TimesheetForm(forms.ModelForm):
    class Meta:
        model = Timesheet
        fields = '__all__'

views.py

def timesheet(request):
if request.method == "POST":
    form = TimesheetForm(request.POST)
    if form.is_valid():
        timesheet = form.save(commit=False)
        timesheet.studentID = request.POST.get('studentID')
        timesheet.studentName = request.POST.get('studentName')
        timesheet.startDate = request.POST.get('startDate')
        timesheet.endDate = request.POST.get('endDate')
        timesheet.save()
        return HttpResponseRedirect(reverse('hrfinance/timesheet.html'))
    #if the form is not valid, redirect the student to the same page
    else:
        form = TimesheetForm()
        return render(request, 'hrfinance/timesheet.html', {'form': form})
else:
    form = TimesheetForm()
    return render(request, 'hrfinance/timesheet.html', {'form': form})
3
  • form.save() not timesheet.save(). Why are you posting the same question two times? Instead ignoring what we suggested you yesterday you could simply read what the people said. Leaving questions where people provided answers and suggestions is super rude but opening the same question on the next day? Very clever. Really, I'm impressed! Commented Jun 29, 2017 at 16:18
  • i got a very strange notifications on stack overflow. To be honest, i didn't receive any notifications on what u replied ytd. I am so sorry for tat Commented Jun 29, 2017 at 16:22
  • @hansTheFranz thank you for you reply anyway. I will report to stackoverflow on the notification thing. Commented Jun 29, 2017 at 16:26

1 Answer 1

3

There are lots of very strange things here.

Firstly, there is no need to set the fields manually on save. That is exactly what form.save() does in the first place. (And if you ever did need to set something manually, you should always get it from form.cleaned_data rather than request.POST.)

Secondly, you re-instantiate the form if it fails validation. That means that the users can never see the errors that are preventing it from validating.

Thirdly, you should show errors in the template. Along with that, you should let Django itself output your fields so that they are automatically prepopulated when the form is invalid.

Finally, you should add your checkbox as a field on the form, so that it is validated along with everything else.

class TimesheetForm(forms.ModelForm):
    checkbox = forms.BooleanField()

    class Meta:
        model = Timesheet
        fields = '__all__'

...

def timesheet(request):
    if request.method == "POST":
        form = TimesheetForm(request.POST)
        if form.is_valid():
            timesheet = form.save()
            return HttpResponseRedirect(reverse('hrfinance/timesheet.html'))
    else:
        form = TimesheetForm()
    return render(request, 'hrfinance/timesheet.html', {'form': form})

...

<form method="POST" onsubmit="return validation()" action="">
    {% csrf_token %}
    {{ form.errors }}

    <div class="content-wrapper">
        <div class="sub-content">
            <div>
                <p>Student ID: {{timesheet.studentID}}</p>
                {{ form.studentID }}
            </div>
        </div>
    </div>
    .... etc...

        <div class="checklist">
            <p>By checking this box I agree that I have satisfied all requirements to continue receiving my scholarship
        allowance.</p>
            {{ form.checkbox }}
        </div>
Sign up to request clarification or add additional context in comments.

7 Comments

is there anyway to make the start and end date have a date picker ? instead of using {{ form.startDate }} and {{ form.endDate }}
after i tried the submit button, i receive this error : ValueError at /hrfinance/timesheet/ The view hrfinance.views.timesheet didn't return an HttpResponse object. It returned None instead.
Apologies, the last line of the view should have had one less indentation level. Try it now.
but i got NameError: global name 'reverse' is not defined
Seriously, this is basic Python now. You need to import reverse, just like you imported everything else.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.