2014-11-12 2 views
2

장고에 ModelFormset이 있습니다.Django Model Formsets, 삭제 옵션의 위치를 ​​변경하십시오.

템플릿에서 양식을 반복하고 양식의 각 필드를 반복합니다 (두 개의 다른 모델에 사용).

{%for form in formset %} 
    <tr class='row{% cycle '2' '1' %}'> 

     {% for hiddenfield in form.hidden_fields%} 
      {{ hiddenfield }} 
     {% endfor %} 


     {% for field in form.visible_fields %} 
      <td>{{ field.errors}}{{ field }}</td> 
     {% endfor %} 
     </tr> 
{% endfor%} 

나는 can_delete = True를 formset_factory에 추가 했으므로 맨 오른쪽에있는 삭제 체크 박스가 나타납니다.

왼쪽에 넣고 이전과 같이 다른 양식 필드를 반복 할 수있는 방법이 있습니까? 필드를 반복 할 때 첫 번째 양식 필드를 만드는 방법이 있습니까?

+0

클래스 또는 이름을 검사 한 다음 CSS를 추가하십시오. – madzohan

답변

3

당신과 같이, 전면에 삭제 필드를 이동의 BaseFormSet의 add_fields 방법을 재정의 할 수 있습니다 : "(ItemsView은"목록에

from collections import OrderedDict 
from django import forms 
from django.forms.formsets import BaseFormSet, formset_factory 
from .models import MyModel 


class MyModelForm(forms.ModelForm): 
    class Meta: 
     model = MyModel 


class BaseMyModelFormSet(BaseFormSet): 

    def add_fields(self, form, index): 
     super(BaseMyModelFormSet, self).add_fields(form, index) 
     # Pop the delete field out of the OrderedDict 
     delete_field = form.fields.pop('DELETE') 
     # Add it at the start 
     form.fields = OrderedDict(
         [('DELETE', delete_field)] + form.fields.items()) 


MyModelFormSet = formset_factory(MyModelForm, BaseMyModelFormSet, 
          extra=2, can_delete=True) 
0

가 난 단지 목록을 연결할 수 없습니다) 형식 오류 "점점 유지 "위의 seddonym의 제안 된 코드로. 파이썬 3에서는 더 쉬운 방법이 있습니다 move an item in OrderedDict to the front. 그래서 다음 코드가 저를 대신했습니다 :

class BaseMyModelFormSet(BaseFormSet): 

    def add_fields(self, form, index): 
     super(BaseMyModelFormSet, self).add_fields(form, index) 
     # Move the delete field to the front end 
     form.fields.move_to_end('DELETE', last=False) 
관련 문제