IIRC, the selection of the Head Boy and Head Girl are not given much detail in the books. They're always 7th Years, and the system seems to favor if not require prefect status. The two Gryffindor prefects we know of (Ron and Hermione) abandon school to follow Harry before they'd have had a shot at it. Besides, with Snape as Headmaster and the Malfoys out of favor, it would be likely we wouldn't be very familiar with whatever Slytherin boy and girl were picked; perhaps Pansy Parkinson and Blaise Zabini.
Anyway, there are a few different ways it could work that make at least some sense. Here's the most sensical system IMHO: Two prefects (one boy, one girl) per House, per year are chosen from the 5th, 6th and 7th years. One Head Boy and Head Girl are chosen from the combination of the four 7th-year Prefects of that gender (one from each House) and any serving Quidditch Captains.
This would allow James Potter, who didn't make prefect in 5th year but was likely good enough on the Quidditch pitch in the later years to be named Captain, a chance at Head Boy. With Dumbledore as the headmaster and thus a slight bias to Gryffindors, James and Lily (who, it's implied, was the Hermione Granger of her day) would be shoo-ins.
Another possibility is that James wasn't originally a prefect, but somehow a spot opened up (hey, Voldemort was very active at that time) and James had deflated his ego enough to be named a replacement. James is never explicitly stated as EVER being a prefect, but if Captains aren't considered, the only way is for him to have gotten Prefect status later on after his 5th year.
The last possibility is, out-of-universe, that JK simply hadn't given much thought to how Head Boy and Girl would work, or to the childhood characters of James and Lily, so when it came time to paint James with the same brush as the Weasley twins (maybe worse), Hagrid's quip of naming James as Head Boy was conveniently ignored.