Carlos Herrera
Carlos Herrera

Reputation: 105

POST doesnt work

Im trying to get the value form a post in django but it pass an empty field `def PersonEmail(request):

Im trying to get the value form a post in django but it pass an empty field `def PersonEmail(request):

if request.method == "POST":
    form1 = PersonForm(request.POST, prefix="form1")
    form2 = EmailForm(request.POST, prefix="form2")
    name = form2['email'].value
    return HttpResponse(name)
else:
    form1 = PersonForm()
    form2 = EmailForm()
    return render(request, 'CreatePersonEmail.html', locals())`

but when i separate them i.e.

Im trying to get the value form a post in django but it pass an empty field `def PersonEmail(request):

if request.method == "POST":
    # form1 = PersonForm(request.POST, prefix="form1")
    form2 = EmailForm(request.POST, prefix="form2")
    name = form2['email'].value
    return HttpResponse(name)
else:
    form1 = PersonForm()
    form2 = EmailForm()
    return render(request, 'CreatePersonEmail.html', locals())`

it gives me the value of the field.

Why? and how can i make it to obtain the values of both forms fields?

Upvotes: 2

Views: 88

Answers (2)

Tom Carrick
Tom Carrick

Reputation: 6616

Basically, you're doing it wrong.

Firstly, you need to check if the form is valid. Users could type any crap in, you don't want to let them do that:

if request.method == "POST":
    form = MyForm(request.POST)
    if form.is_valid():
        # Now you can access the fields:
        name = form.cleaned_data['name']

If the form isn't valid, just pass it back to render() and it will show the errors.

Also, don't do this:

return render(request, 'CreatePersonEmail.html', locals())`

Build your context dictionary properly, don't use locals(), it's hacky and you pollute your context.

So a full view might look like this (taken from django docs and changed a bit:

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():
            name = form.cleaned_data['name']
            return render(request, 'some_page.html', {'name': name})

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

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

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599946

You need to use the prefix both times you instantiate the forms; both on GET and on POST.

Also, you get values from the form's cleaned_data dict, not from the field.

Upvotes: 1

Related Questions