Django模板表单没有发布

时间:2015-04-02 15:59:43

标签: python html django post django-forms

我正在做一个应用程序,由于一些奇怪的原因,我无法将表单的值存储到数据库中。 问题是数据不是通过POST发送的,因此我的视图不会收集它们。这是什么原因? 我的(简化)模板代码:

{% block content %}
<form action = "{%url 'bodySettings' %}" method = "POST">
    {% csrf_token %}
    {{ form }}
    <input type = "submit" value = "Save"/>
</form>

{% endblock content %}

我的django观点:

@login_required
@csrf_protect
def bodysettings(request):

    properties_Form = BodyPropertiesForm()


    if request.method == 'POST':
        print ("test")
        if properties_Form.is_valid():

            properties = properties_Form.save(commit = False)
            properties.user = request.user
            properties.save()

            return HttpResponseRedirect('/home/')

    args = {}
    args.update(csrf(request))
    args['request'] = request
    args['form'] = properties_Form

    return render_to_response('stats_test.html',args)

我的forms.py:

    from django import forms
    from django.contrib.auth.models import User
    from models import Body

    class BodyPropertiesForm(forms.ModelForm):
    MALE = 'M'
    FEMALE = 'F'
    GENDER_CHOICE = (
    (MALE, 'male'),
    (FEMALE, 'female'),
    )

gender      = forms.ChoiceField(choices = GENDER_CHOICE, required = True, 
    help_text = "Select your gender")
height      = forms.IntegerField(required = True, help_text = "Enter your height")
weight      = forms.IntegerField(required = True, help_text = "Enter your body weight" )
neck        = forms.IntegerField(required = True, help_text = "Enter your neck size")
shoulders   = forms.IntegerField(required = True, help_text = "Enter your width")
chest       = forms.IntegerField(required = True, help_text = "Enter your chest size")
arm         = forms.IntegerField(required = True, help_text = "Enter your arm size")
wrist       = forms.IntegerField(required = True, help_text = "Enter your wrist size")
hips        = forms.IntegerField(required = True, help_text = "Enter your waist size ")
waist       = forms.IntegerField(required = True, help_text = "Enter your hips size")
thigh       = forms.IntegerField(required = True, help_text = "Enter your thigh size")
calf        = forms.IntegerField(required = True, help_text = "Enter your calf size")

class Meta:
    model = Body
    fields = ('gender','height','weight','neck','shoulders','chest','arm','wrist',
        'waist','hips','thigh','calf')
    exclude = ('user',)

2 个答案:

答案 0 :(得分:2)

您未将POST值传递给表单。

if request.method == 'POST':
    properties_Form = BodyPropertiesForm(request.POST)

答案 1 :(得分:0)

您可以在终端中看到是post还是get请求。我认为这里的数据是postquery dict为空的问题是因为,< / p>

class NameForm(forms.Form):
    your_name = forms.CharField(label='myfieldname', max_length=100)

所以label应该在表单中。这可以在view中以request.POST['myfieldname']获取。此外,您必须使用

properties_Form = BodyPropertiesForm(request.POST) 

希望这有帮助