Django,从POST中获取值

时间:2017-01-31 14:20:00

标签: python django

我的模板中有:

This is passed by {{form}}

    <form action="" method="POST">
        Inicio: <input type="text" id="start">
        <input type="submit" value="Sned" >
     {% csrf_token %}
    </form>

然后在views.py

def test(request):

    if request.method != 'POST':
        context = {'form': 'by GET'}
        return render(request, 'test.html', context)
    else:

        if 'start' in request.POST:
            start = request.POST['start']
        else:
            start = False


    context = {'form': start}
    return render(request, 'test.html', context)

似乎总是返回False

如果我不检查密钥的存在,我有这个错误:

MultiValueDictKeyError 

并且错误说:“'开始'”(单加双引号)

3 个答案:

答案 0 :(得分:4)

#include <regex.h> #include <string.h> #include <stdio.h> #include <stdlib.h> typedef struct match_s match_t; struct match_s { int beg; match_t *next; }; int main(int argc, const char *argv[]) { char *str = strdup("aaaaaaa match aaaaaaaaaaaaaaaaaaaa\n" "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" "cc match ccccccccccccccccccccccccc"); match_t *head = NULL; match_t *tail = NULL; char *c = str; regex_t regex; regmatch_t match; regcomp(&regex, "match", REG_EXTENDED); int prev = 0; while(regexec(&regex, str, 1, &match, 0) != REG_NOMATCH) { int beg = match.rm_so; int end = match.rm_eo; str = str + end + 1; match_t *match = malloc(sizeof(match_t)); match->beg = beg + prev; match->next = NULL; prev += end+1; if(head == NULL) { head = match; tail = match; } else { tail->next = match; tail = match; } } int line = 0; int i = 0; for(i = 0; c[i] != '\0' && head != NULL; i++) { if(c[i] == '\n') { line++; } else if(head->beg == i) { printf("Match on line: %d\n", line); match_t *tmp = head->next; free(head); head = tmp; } } free(str); return 0; } 用于javascript和css目的。对于服务器端重要的变量,应使用id标记。

name

答案 1 :(得分:3)

您需要在输入中添加name属性,因此当您获取POST数据时,它将被找到。

request.POST['start']

另外,我建议您在视图中进行以下更改:

替换

request.POST.get('start')

由:

None

因此,如果找不到该字段,则会以{{1}}值重新分配该字段。

答案 2 :(得分:2)

添加名称

View