Django forms: passing variables to a modelchoicefield

 

So I came across the problem of needing to filter my Django ModelChoiceField queryset by a variable in my view. Specifically I needed to pass the current selected state to the ModelChoiceField queryset. The best way I found to do this is to initialize the form with my state var in the initial:

  1. state = ‘OH’
  2. form = LocationForm(initial={‘state’:state})

After that, instead of creating the field the traditional way, you can append the field to the self.fields dictionary within the init, enabling you to pass the initial state variable into the queryset of the field. Here is my form:

  1. class LocationForm(forms.Form):
  2.     def __init__(self, *args, **kwargs):
  3.         super(LocationForm, self).__init__(*args, **kwargs)
  4.         self.fields.insert(len(self.fields)-1‘location’,
  5.                            forms.ModelChoiceField(queryset=Location.objects.filter(state=self.initial[‘state’])))
  6.     first_name = forms.CharField(50, label=“First Name”)
  7.     last_name = forms.CharField(50, label=“Last Name”)
  8.     address = forms.CharField(60, label=“Street Address”)
  9.     city = forms.CharField(40, label=“City”)
  10.     state = USStateField()
  11.     zip = USZipCodeField()

Self.fields is a Django SortedDict, and it’s insert method takes the index to insert to, the key, and the value.

Source

La clave del éxito: por Laura Federico @adinteractiva


De niños nos preguntaban ¿Qué es lo que querés ser cuando seas grande? Casi siempre las respuestas eran: astronauta, bombero, policía, médico, bailarina. Y ahora, que llegamos a grandes, ¿en qué nos convertimos?

Cuando miramos hacia atrás en la vida, podemos ver una gran cantidad de logros obtenidos, pero cuando observamos hacia el futuro, tratando de definir lo que queremos alcanzar, la visualización se torna nebulosa.
– See more at: http://administracioninteractiva.com/la-clave-del-exito-2/#sthash.omsfGJbE.dpuf

Convert Object To Array With PHP

By Kevin Waterson

Converting an object to an array using PHP comes with a small gotcha. One would be forgiven for thinking it is merely a task of casting the object and the job can be completed with a single line of code. This works well for simple objects, however, the task increases in complexity in line with the objects complexity.

Consider the following object that is cast to an array.


<?php
/*** create an object ***/
$obj = new stdClass;
$obj->foo = 'foo';
$obj->bar = 'bar';
$obj->baz = 'baz';

/*** cast the object ***/
$array = (array) $obj;

/*** show the results ***/
print_r( $array );
?>

Gracias a PHPro