On Sep 23, 4:44 pm, BobZ <[EMAIL PROTECTED]> wrote: > Thanks Daniel. I've found solutions similar to yours in other threads > on the net, and everytime I test them, I literally get no form at all > in my rendered template. > My template appears to have all the correct code in it as you can see > in the link "search.html" at the bottom of this post. > Looking at the code you provided, it seems like the > "queryset=Vehicle.objects.order_by('-year').distinct()" pulls all > distinct fields from the Vehicle table and sorts them by year. What > I'm actually after is a way to filter out only the years and list them > in descending order. > > In my forms.py file, I've kept all variations of the code I've tested > for this app commented out for my own reference, but maybe it will > help you see what's happening and what I'm trying to do. > > Here's all of my code in dpaste: > <a href="http://dpaste.com/80010/">models.py -http://dpaste.com/80010/</a> > <a href="http://dpaste.com/80009/">forms.py -http://dpaste.com/80009/</a> > <a href="http://dpaste.com/80011/">views.py -http://dpaste.com/80011/</a> > <a href="http://dpaste.com/80013/">search.html -http://dpaste.com/80013/</a>
I think you're misunderstanding the point of ModelForms. A ModelForm (as opposed to a standard form) is specifically for creating or editing a model instance. So if you had a model with a foreignkey to Vehicle, you could use this model as the base for a modelform with the modelchoice field we have defined. However, you have defined a ModelForm based on the Vehicle model, with a modelchoice field also pointing at Vehicle. That doesn't make sense, as the year field on Vehicle isn't a ForeignKey, it's an IntegerField. This could be why you're not getting any output in the rendered template. Luckily, your use case doesn't warrant a ModelForm anyway. You're not editing a model, you are using the form to create a search box. So you just want a standard Form. In which case, something akin to dmorozov's solution may be best after all. How about this: class SearchForm(forms.Form): year=forms.ChoiceField() def __init__(self, *args, **kwargs): super(SearchForm, self) .__init__(*args, **kwargs) self.fields['year'].choices = Vehicle.objects.values_list('year', 'year').distinct().order_by('- year') -- DR. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---