2012-08-14 29 views
6

he campo de formulario {{}} form.item, que pagará aCambiar el atributo de nombre de campo de formulario en la plantilla de Django usando

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

¿Cómo puedo cambiar el atributo de nombre del campo de formulario utilizando ¿etiquetas de plantilla personalizadas?

me trataron enviando el formulario de etiqueta de plantilla, donde

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

Pero no voy a conseguir el éxito.

Necesito cambiar el nombre del atributo en la plantilla.

ACTUALIZACIÓN

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, 
     } 

plantilla

<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> 

Ahora en etiqueta de plantilla personalizada que necesito para asignar nuevo nombre para cada campo de juego de formularios en línea

+0

posible duplicado de [Reemplazar atributo 'name' del campo de formulario de Django] (http://stackoverflow.com/questions/8801910/override-django-form-fields-name-attr) – mgibsonbr

+1

Por qué ¿quieres cambiar el nombre? ¿Qué te hace pensar que necesitas esto? –

+0

Er, ¿qué? Ninguno de estos es un motivo para usar nombres dinámicos. Explique su caso de uso y por qué no está cubierto por la estructura de vista/conjunto de formularios estándar. –

Respuesta

0

Usted puede subclase cualquier clase widget de lo que necesita y crear su propia "render método". Los ejemplos están en los/django/formas PATH_TO_YOUR_DJANGO/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

No veo dónde estás están especificando un nuevo nombre para el atributo de nombre de campo – Asif

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

@Sergy: ya probé este, pero en mi caso esto no funcionará porque estoy tratando con formset – Asif

4

He probado esto varias maneras diferentes, y funciona con muchos tipos de campos de formulario.

Use set_field_html_name(...) en cada campo que desee establecer el nombre.

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'})) 
Cuestiones relacionadas