0

I'm getting values from form in django like this:

            tantou1 = request.POST.get("1tantou", "")
            tantou2 = request.POST.get("2tantou", "")
            tantou3 = request.POST.get("3tantou", "")
            tantou4 = request.POST.get("4tantou", "")

            hidzuke1 = request.POST.get("1hidzuke", "")
            hidzuke2 = request.POST.get("2hidzuke", "")
            hidzuke3 = request.POST.get("3hidzuke", "")
            hidzuke4 = request.POST.get("4hidzuke", "")

which works, but I have a lot of values to get and this way took too much space in my code. I would like to ask, if there is not a way to define this variables in (for example) loop? Something like:

data_vars = [tantou1="", tantou2="", tantou3="", tantou4="", hidzuke1="", hidzuke2="", hidzuke3="", hidzuke4=""]

for var in data_vars:
    var = request.POST.get(str(var.__name__), "")

or so?

Marcel Kopera
  • 304
  • 2
  • 9

2 Answers2

2

You should just pass request.POST into your form's __init__, like so:

def view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)

        if form.is_valid():
            form.save()
    else:
        ...
Lord Elrond
  • 13,430
  • 7
  • 40
  • 80
1

The docs say that HttpRequest.POST is a dictionary-like object.

According to this post you can unpack a dict to variables a number of ways, but they recommend namespacing. I've just tried this and it works:

from types import SimpleNamespace 

n = SimpleNamespace(**request.POST.dict())

You can then access your variables as:

n.tantou1
n.tantou2
MattRowbum
  • 2,162
  • 1
  • 15
  • 20