一页中的Django向导表单和其他视图

时间:2018-08-30 20:15:18

标签: python django django-forms django-formwizard

我试图在一个页面中显示一个向导表单和一个表(由该表单生成,并且可以在每个步骤中看到)。有可能吗?

我尝试过:

urls.py

urlpatterns = [url('', GroupsWizard.as_view(form_list), name = 'index'),]

views.py

def index(request):
    groups_render = Groups.objects.all()
    return render(request, 'index.html', {'groups_render' : groups_render})

class GroupsWizard(SessionWizardView):

    def get_template_names(self):
        return 'index.html'

    def done(self, form_list, **kwargs):
        data = {k: v for form in form_list for k, v in form.cleaned_data.items()}
        instance = Groups.objects.create(**data)
        return render(self.request, 'done.html', {
            'form_data': [form.cleaned_data for form in form_list],
        })

index.html

<div>
  {{ wizard.form.management_form }}
    {% for form in wizard.form.forms %}
      {{ form }}
    {% endfor %}
</div>
<div>
{{ groups_render }}
</div>

谢谢

1 个答案:

答案 0 :(得分:0)

我找到了,

我在views.py中使用了get_context_data函数:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, ValidationErrors, ValidatorFn, FormBuilder, Validators } from '@angular/forms';

const myValidator: ValidatorFn = (formGroup: FormGroup): ValidationErrors | null => {
  // get controls
  const name = formGroup.get('name');
  const myCheckbox = formGroup.get('myCheckbox');

  // validate however needed, e.g. length/pattern/etc
  const isNameValid: boolean = name && name.value && name.value.length > 0;
  const isCheckboxValid: boolean = myCheckbox && myCheckbox.value && myCheckbox.value === true;

  // return null if valid otherwise return object with custom key/value
  return (isNameValid || isCheckboxValid) ? null : { 'formValid': false };
};

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  myFormGroup: FormGroup;
  name = 'Angular';

  constructor(private fb: FormBuilder) { }

  onSubmit() {
    console.log('submitted!');
  }

  ngOnInit() {
    // key thing here is passing the ValidatorFn as the 2nd argument to expose the FormGroup in the ValidatorFn rather than a FormControl
    this.myFormGroup = new FormGroup({
      'name': new FormControl(),
      'myCheckbox': new FormControl()
    }, { validators: myValidator });
  }
}