2012-08-14 22 views
6

Mam pole formularza {{}} form.item który oddaZmień atrybut name pola formularza w szablonie django użyciu

 <input type="text" name="item" > 

Jak mogę zmienić atrybut nazwa pola formularza za pomocą niestandardowe tagi szablonów?

Próbowałem wysyłając formularz do szablonu tagu gdzie

 form.fields['item'].widget.attrs['name'] = 'new_name' 

Ale nie jestem uzyskania sukcesu.

Potrzebuję zmienić atrybut nazwy w szablonie.

UPDATE

models.py

class A(models.Model): 
    name = models.CharField(50) 
    type = models.CharField(50) 

class B(models.Model): 
    field1 = ForeignKeyField(A) 
    value = IntegerField() 

views.py

def saving_calculation(request): 

    SavingFormset = modelformset_factory(A, extra=2) 
    OfferInlineFormSet = inlineformset_factory(
        A, B, 
        extra = 4 
        ) 

    if request.method == 'POST': 
     pass 
    else: 
     offer_formset = OfferInlineFormSet() 
     saving_formset = SavingFormset(queryset=SavingCalculation.objects.none()) 

    return render_to_response(
     'purchasing/saving_calculation.html', 
     { 
     'offer_formset':offer_formset, 
     'saving_formset':saving_formset, 
     } 

szablon

<form action="." method="POST"> 
    {{ offer_formset.management_form }} 
    {{ saving_formset.management_form }} 
    {{ saving_formset.prefix }} 
    <table> 
<thead> 
    <tr> 
     <th>Business Unit</th> 
    <th>Category</th> 
    <th>Buyer</th> 
    <th>Offer1</th> 
    <th>Offer2</th> 
    <th>Offer3</th> 
    <th>Offer4</th> 
    </tr> 
    </thead> 
<tbody> 
     {% for saving in saving_formset.forms %} 
    <tr> 
    <td>{{saving.businessunit}}</td> 
    <td>{{saving.type_of_purchase}}</td> 
    <td>{{saving.buyer}}</td> 
    {% for offer in offer_formset.forms %} 
     <td>{{ offer|set_field_attr:forloop.counter0 }}</td> 
    </tr> 
     {% endfor %} 

    {% endfor %} 

     </tbody> 
    </table> 
    <input type="submit" value="Save" /> 
    </form> 

Teraz w tagu niestandardowego szablonu muszę przypisać nową nazwę dla każdej dziedziny inline formset

+0

możliwe duplikat [przesłanianie formularz Django polu za nazwisko attr] (http://stackoverflow.com/questions/8801910/override-django-form-fields-name-attr) – mgibsonbr

+1

Dlaczego czy chcesz zmienić nazwę? Co sprawia, że ​​myślisz, że tego potrzebujesz? –

+0

Er, co? Żadne z nich nie jest powodem używania nazw dynamicznych. Wyjaśnij swój przypadek użycia i dlaczego nie jest on objęty standardową strukturą widoku/zestawu formularzy. –

Odpowiedz

0

Można podklasa dowolnej klasy widget czego potrzebujesz i tworzyć własne „render metody”. Przykładami są w PATH_TO_YOUR_DJANGO/Django/form/forms.py

class CustomNameTextInput(TextInput): 
    def render(self, name, value, attrs=None): 
     if 'name' in attrs: 
      name = attrs['name'] 
      del attrs['name'] 
     return super(TextInput, self).render(name, value, attrs) 


class MyForm(Form): 
    item = CharField(widget=CustomNameTextInput, attrs={'name':'my_name'}) 
+0

Nie widzę, gdzie jesteś określają nową nazwę dla atrybutu nazwy pola – Asif

2
form.fields['new_name'] = form.fields['item'] 
del form.fields['item'] 
+0

@Sergy: Próbowałem już tego, ale w moim przypadku to nie zadziała, ponieważ mam do czynienia z formsetem – Asif

4

Przetestowałem to na kilka różnych sposobów, i współpracuje z wieloma typami pól formularza.

Użyj set_field_html_name(...) na każdym polu, na którym chcesz ustawić nazwę.

from django import forms 
from django.core.exceptions import ValidationError 

def set_field_html_name(cls, new_name): 
    """ 
    This creates wrapper around the normal widget rendering, 
    allowing for a custom field name (new_name). 
    """ 
    old_render = cls.widget.render 
    def _widget_render_wrapper(name, value, attrs=None): 
     return old_render(new_name, value, attrs) 

    cls.widget.render = _widget_render_wrapper 

class MyForm(forms.Form): 
    field1 = forms.CharField() 
    # After creating the field, call the wrapper with your new field name. 
    set_field_html_name(field1, 'new_name') 

    def clean_field1(self): 
     # The form field will be submit with the new name (instead of the name "field1"). 
     data = self.data['new_name'] 
     if data: 
      raise ValidationError('Missing input') 
     return data 
1
class MyForm(forms.ModelForm): 
    def __init__(self, *args, **kwargs): 
     super(MyForm, self).__init__(*args, **kwargs) 
     self.fields['field_name'].label = "New Field name" 
0
from django.forms.widgets import Input, TextInput 


class CustomInput(Input): 
    def get_context(self, name, value, attrs): 
     context = super(CustomInput, self).get_context(name, value, attrs) 
      if context['widget']['attrs'].get('name') is not None: 
       context['widget']['name'] = context['widget']['attrs']['name'] 
     return context 


class CustomTextInput(TextInput, CustomInput): 
    pass 


class ClientLoginForm(forms.Form): 

    username = forms.CharField(label='CustomLabel', widget=CustomTextInput(attrs={'class': 'form-control','name': 'CustomName'})) 
Powiązane problemy