Home > Software design >  Why we write this, form = StudentForm(request.POST) in django?
Why we write this, form = StudentForm(request.POST) in django?

Time:02-19

This is my views function,

def studentcreate(request):
    reg = StudentForm()
    string = "Give Information"

    if request.method == "POST":
        reg = StudentForm(request.POST)
        string = "Not Currect Information"

        if reg.is_valid():
            reg.save()
            return render('http://localhost:8000/accounts/login/')

    context = {
        'form':reg,
        'string': string,
    }

    return render(request, 'student.html', context)

Here first we store form in reg variable then also we write reg = StudentForm(request.POST) why? acutally why we write this?

CodePudding user response:

I can't tell you why you are writing this. Maybe only you know. It does not make much sense. I would recommend reading the Django documentation on this at https://docs.djangoproject.com/en/4.0/topics/forms/#the-view

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import NameForm

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})

You read from data if the request is a POST. Otherwise, return an empty form.

CodePudding user response:

You could think of the "request.POST" as a parameter passed onto the form in the view. This tells the view that the form mentioned has POST data from the form in name.html. Otherwise it is just an empty form.

  • Related