2016-02-09 8 views
1

Я пытаюсь использовать FormWizard, чтобы сделать регистрацию для новых пользователей. Потому что в некоторых случаях мне нужно будет использовать js, formsets и photos, я решил сделать другой шаблон для каждого шага. Но потом я получил ошибку:Django FormWizard с различными шаблонами

ValidationError at /registration_steps 
[u'\u0414\u0430\u043d\u043d\u044b\u0435 ManagementForm \u043e\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u044e\u0442 \u0438\u043b\u0438 \u0431\u044b\u043b\u0438 \u0438\u0441\u043a\u0430\u0436\u0435\u043d\u044b.'] 

forms.py

class ApplicantForm1(forms.ModelForm): 
    password1 = forms.CharField(
     label='Password', 
     widget=forms.PasswordInput 
    ) 
    password2 = forms.CharField(
     label='confirm', 
     widget=forms.PasswordInput 
    ) 
    travel_passport = forms.ChoiceField(
     choices=((False, 'Нет'), (True, 'Да')), 
     widget=forms.Select 
    ) 
    def clean_password2(self): 
     password1 = self.cleaned_data.get('password1') 
     password2 = self.cleaned_data.get('password2') 
     if password1 and password2 and password1 != password2: 
      raise forms.ValidationError('Passwords dont match') 
     return password2 

    def save(self, commit=True): 
     user = super(ApplCreaForm, self).save(commit=False) 
     user.set_password(self.cleaned_data['password1']) 
     user.isempl=0 
     if commit: 
      user.save() 
     return user 
    class Meta: 
     model = ExtUser 
     fields = ['email','firstname', 'lastname', 'middlename', 'date_of_birth', 'gender', 'family_position', 
        'driver_license', 'driver_license_category',] 

class ApplicantForm2(forms.ModelForm): 
    class Meta: 
     model = ExtUser 
     fields = ['country','region','city', 'nearcity', 'travel_passport', 'travel_passport_end_date','metro', 'mobile_sms', 'mobile_double', 'email_double', 
        'web', 'vkontakte', 'facebook','odnoklasniki','skype','whatsapp','viber','ready_to_move','ready_to_move_where',] 

views.py

FORMS_REG = [("reg_step1", ApplicantForm1), 
     ("reg_step2", ApplicantForm2), 
     # ("ApplicantForm3", ApplicantForm3), 
     # ("ApplicantForm4", ApplicantForm4), 
     # ("ApplicantForm5", ApplicantForm5), 
     # ("ApplicantForm6", ApplicantForm6), 
     # ("ApplicantForm7", ApplicantForm7), 
     ]   

TEMPLATES_REG = {"reg_step1": "registration_steps/reg_step1.html", 
      "reg_step2": "registration_steps/reg_step2.html", 
      #"reg_step3": "registration_steps/reg_step3.html", 
      #"reg_step4": "registration_steps/reg_step4.html", 
      #"reg_step5": "registration_steps/reg_step5.html", 
      #"reg_step6": "registration_steps/reg_step6.html", 
      #"reg_step7": "registration_steps/reg_step7.html", 
      } 

class ApplicantWizard(SessionWizardView): 
    instance = None 
    def get_template_names(self): 
     return [TEMPLATES_REG[self.steps.current]] 
    def get_form_instance(self, step): 
     if self.instance is None: 
      self.instance = ExtUser() 
     return self.instance 
    def done(self, form_list, **kwargs): 
     self.instance.save() 
     return render_to_response('app/successpage.html', { 
      'title':"Registration complited" , 
     }) 

urls.py

url(r'^registration_steps$', ApplicantWizard.as_view(FORMS_REG)), 

шаблоны reg_step1.html и reg_step2.html (сейчас они такие же)

{% extends "layout/layout_main.html" %} 

{% block content %} 
<p> Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> 
{% for field in form %} 
    {{field.error}} 
{% endfor %} 

<form action="" method="post">{% csrf_token %} 
<table> 
{{wizard.managment_form}} 
    {{ wizard.form }} 
</table> 
{% if wizard.steps.prev %} 
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">"first step"</button> 
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"prev step"</button> 
{% endif %} 

<input type="submit" value="Submit" /> 
</form> 
{% endblock %} 
+0

В сообщении об ошибке написано, что ваша форма управления отсутствует. Дважды проверьте, содержат ли ваши шаблоны строку '{{wizard.managment_form}}'. –

+0

Да, оба шаблона содержат эту строку. –

ответ

0

Как мастер формы жалуется на недостающую форму управления, проблема, как представляется, связано с вложенными FormSets. Сделайте свою соответствующую страницу шаблонов:

<table> 
    {{ wizard.management_form }} 
    {% if wizard.form.forms %} 
     {{ wizard.form.management_form }} 
     {% for form in wizard.form.forms %} 
      {{ form }} 
     {% endfor %} 
    {% else %} 
     {{ wizard.form }} 
    {% endif %} 
</table> 
+0

Да, это помогает. Но теперь у меня другая проблема. Мне нужно установить пароль для пользователя. Iam, используя somthing, как def done (self, form_list, ** kwargs): user = ExtUser() user = self.instance.save() user.set_password (self.cleaned_data ['password1']) user.save(), но получил ошибку. Объект «NoneType» не имеет атрибута «set_password» –

+0

'Model.save()' не возвращает экземпляр self. Вы должны пойти с чем-то вроде 'self.instance.set_password (...)'. –

+0

past_data = self.get_all_cleaned_data() self.instance.set_password (past_data (['password1'])) self.instance.save получил 'dict' объект не вызываемый –

Смежные вопросы