我需要根據需要多次克隆表單。我的目標是:用戶選擇他需要多少股票,然後用相同數量的表單重定向到頁面(可能我應該使用像Ajax這樣的東西,但現在對我來說太難了)。發現我應該使用formset
。現在我有錯誤ManagementForm data is missing or has been tampered with
使用django formset時出錯
使用django-datetime-widget
和django-crispy-forms
forms.py
:
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import *
from crispy_forms.bootstrap import *
from datetimewidget.widgets import DateWidget
class InputDates(forms.Form):
Date_start = forms.DateField(widget=DateWidget(
# attrs={'id':"datetimeid1"},
usel10n = True,
bootstrap_version=3
),
label='first date',
required=True,
)
Date_end = forms.DateField(widget=DateWidget(
# attrs={'id':"datetimeid2"},
usel10n = True,
bootstrap_version=3
),
label='last date',
required=True,
)
Stock = forms.ChoiceField(
choices=( ('GG', 'Google'),
('APPL', 'Apple'),
('SR', 'Smth1'),
('GZ', 'Smth2'),),
required=True,
label='Choose your stock'
)
def __init__(self, *args, **kwargs):
super(InputDates, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Field('Stock'),
Field('Date_start'),
Field('Date_end'),
)
class BTN(forms.Form):
def __init__(self, *args, **kwargs):
super(BTN, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
ButtonHolder(
Submit('submit', 'Make graph', css_class='btn btn-default')
),
)
views.py
:
from django.shortcuts import render
from .forms import *
from django.forms.formsets import formset_factory
def stocks(request):
btn = BTN(request.POST or None)
StocksFormset = formset_factory(InputDates, extra=2)
if request.method == 'POST':
formset = StocksFormset(request.POST)
if formset.is_valid():
return render(request, 'home.html')
else:
formset = StocksFormset()
return render(request, 'stocks.html', {'formset' : formset, 'BTN' : btn})
stocks.html
:
{% extends "base.html" %}
{% load staticfiles %}
{% load crispy_forms_tags %}
{% block content %}
<form action="" method="post" class="text-left">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{% crispy form form.helper %}
{% endfor %}
</form>
{% crispy BTN BTN.helper %}
{% endblock %}
在Django
文檔formset
我發現我應該使用{{ formset.management_form }}
,一切都會好的,但它不適合我。