Django validation of number from query string

Viewed 201

Im having this code to create and add students to database. I need to make validation of count which must be integer, only positive, equal or less 100. Please help.

def generate_students(request):
    count = request.GET.get('count')
    studentslist = []
    for student in range(0, int(count)):
        student = Student.objects.create(first_name = fake.first_name(), last_name = fake.last_name(), age = random.randint(18,100))
        studentslist.append(student)
    output = ', '.join(
        [f"id = {student.id} {student.first_name} {student.last_name}, age = {student.age};" for student in studentslist]
                      )
return HttpResponse(str(output))
1 Answers

The best way is likely to work with a form, since a form has a lot of validation inplace, can clean the object, and print sensical errors.

We thus can work with a simple form:

from django import forms

class CountForm(forms.Form):
    count = forms.IntegerField(min_value=1, max_value=100)

then we can validate the input with:

def generate_students(request):
    form = CountForm(request.GET)
    if form.is_valid():
        count = form.cleaned_data['count']
        studentslist = [
            Student.objects.create(first_name = fake.first_name(), last_name = fake.last_name(), age = random.randint(18,100))
            for _ in range(count)
        ]
        output = ', '.join(
            [f'id = {student.id} {student.first_name} {student.last_name}, age = {student.age};'
             for student in studentslist]
        )
    else:
        return HttpResponse(str(form.errors))
    return HttpResponse(str(output))

Note: Section 9 of the HTTP protocol specifies that requests like GET and HEAD should not have side-effects, so you should not change entities with such requests. Normally POST, PUT, PATCH, and DELETE requests are used for this. In that case you make a small <form> that will trigger a POST request, or you use some AJAX calls.

Related