user5466566
user5466566

Reputation:

Django save data from forms to database

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})

Upvotes: 0

Views: 2002

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599470

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>

Upvotes: 3

Related Questions