不显示输入字段的csrf标记 - Django

时间:2017-06-26 14:03:04

标签: django forms csrf

我是django的新手。我正在使用django==1.11

我正在尝试创建一个输入用户详细信息的表单。

views.py

from django.shortcuts import render, render_to_response, redirect
from django.template import loader, Template, Context, RequestContext  
from forms import UserForm
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators import csrf

def action(request):
    if request.POST:
        form = UserForm(data = request.POST)
        if form.is_valid():
            form.save(commit = False)

            return HTTPResponseRedirect('/rfid/index')
    else:
        form = UserForm()

    args = {}
    args.update(csrf(request))

    args['form'] = form

    return render_to_response('reg.html', args)

forms.py

from django import forms
from models import UserDetails

class UserForm(forms.ModelForm):

    class Meta:
        model = UserDetails
        fields = '__all__'

reg.html

{% extends "rfid/header.html" %}

{% block content %}
<div class="container">
    <form action = "/" method="post">{% csrf_token %}
        <ul>

        {{ form.as_ul }}

        </ul>   

        <input type="submit" name="submit" class="btn btn-default" value="Add User">
    </form>
</div>

{% include "rfid/includes/htmlsnippet.html" %}

{% endblock %}

models.py

from django.db import models

# Create your models here.

class UserDetails(models.Model):
    GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'))
    user_id = models.IntegerField(primary_key = True) 
    name = models.TextField(max_length = 50)
    gender = models.CharField(max_length = 1, choices = GENDER_CHOICES)
    dob = models.DateTimeField()
    address = models.TextField(max_length = 200)
    phone = models.IntegerField()
    email = models.EmailField(max_length=254)
    photo_url = models.CharField(max_length = 200)

    def __str__(self):
        return self.name

但它只显示提交按钮。基于模型的字段未显示。我在这里遇到了一些问题,但无法找出问题所在。任何人都可以帮助我。

希望提供所有必需的细节。请问我是否遗漏了什么。

问候。

1 个答案:

答案 0 :(得分:-1)

使用form.save(commit=False)检出一行。
除了要给该行起一个名称,然后再将名称保存为saved_form=form.save(commit=False)然后再命名为saved_form.safe之外,不需要commit=False行。我不知道这是否是问题,但会检查并还原