如何在Django中将非ModelForm表单保存到数据库

时间:2014-08-13 13:59:07

标签: python django forms

我是一名新手Django用户,他正在努力将表单数据提交到数据库。因此,我可以生成动态表单,我使用非ModelForm 表单来捕获字段数据。

我现在注释掉了验证,但我试图将POST数据从表单捕获到数据库。最新的草稿'我的views.py代码如下 - 最感兴趣的是来自form_to_save = Scenario(...)的格式:

def scenario_add(request, mode_from_url):
    urlmap = {
        'aviation': 'Aviation',
        'maritime': 'Maritime',
        'international_rail': 'International Rail',
        'uk_transport_outside_london': 'UK Transport (Outside London)',
        'transport_in_london': 'Transport in London',
    }
    target_mode = urlmap[mode_from_url]
    m = Mode.objects.filter(mode=target_mode)
    tl = m[0].current_tl.threat_l
    scenario_form = ScenarioForm(request.POST or None, current_tl=tl, mode=target_mode)
    if request.method == 'POST':
        #if scenario_form.is_valid():
        form_to_save = Scenario(
            target = Target(descriptor = scenario_form.fields['target']),
            t_type = ThreatType(t_type = scenario_form.fields['t_type']),
            nra_reference = NraReference(nra_code = scenario_form.fields['nra_reference']),
            subt = scenario_form.fields['subt'],
            ship_t = ShipType(ship_t = scenario_form.fields['ship_t']),
            likelihood = scenario_form.fields['likelihood'],
            impact = scenario_form.fields['impact'],
            mitigation = scenario_form.fields['mitigation'],
            compliance_score = scenario_form.fields['compliance_score'],
            notes = scenario_form.fields['notes']
        )
        form_to_save.save()
        # This needs to be changed to a proper redirect or taken to
        # a scenario summary page (which doesn't yet exit.)
        return render(request, "ram/new_scenario_redirect.html", {
            'scenario_form': scenario_form,
            'mode': mode_from_url,
            'mode_proper': target_mode
        })
    else:
        # if there is no completed form then user is presented with a blank
        # form
        return render(request, 'ram/scenario_add.html', {
            'scenario_form': scenario_form,
            'current_tl': tl,
            'mode': mode_from_url,
            'mode_proper': target_mode
        })

感激地收到任何建议。非常感谢。

2 个答案:

答案 0 :(得分:0)

由于某种原因,您已对is_valid支票进行了评论。您需要:除了检查有效性之外,它还会填充表单的cleaned_data字典,这是您应该从中创建对象的数据。 (并且不要将该对象称为“form_to_save”:它是模型实例,而不是表单)。

if request.method == 'POST':
    if scenario_form.is_valid():
        scenario = Scenario(
            target = Target(descriptor=scenario_form.cleaned_data['target']),
            t_type = ThreatType(t_type = scenario_form.cleaned_data['t_type'])
            ...etc

另外,您应该将最终的“return render”调用移出else块,以便在表单有效时捕获它,以显示任何错误。

然而,正如petkostas所说,你几乎肯定会首先使用实际的ModelForm。

答案 1 :(得分:0)

您可以通过覆盖表单中的 init 功能来添加自定义选项。例如:

class SomeForm(forms.Form):
    department = forms.ChoiceField(widget=forms.Select, required=True)

...

    def __init__(self, *args, **kwargs):
        super(SomeForm, self).__init__(*args, **kwargs)
        self.fields['department'].choices = Department.objects.all().order_by('department_name).values_list('pk', 'department_name')

您还可以在init函数中更改查询集: 其中Department是外键,例如

queryset = Department.objects.filter(your logic)
self.fields['department'].queryset = queryset