On Mon, Oct 24, 2011 at 2:57 PM, Tom Evans <[email protected]> wrote:
> On Mon, Oct 24, 2011 at 11:14 AM, Kayode Odeyemi <[email protected]> > wrote: > > Hello all, > > > > class BranchModelChoiceField(ModelChoiceField): > > def label_from_instance(self, obj): > > return obj > > > > class TransactionUpdateForm(forms.ModelForm): > > branchqs = Branch.objects.values_list(u'name_branch', flat=True) # > use > > flat=True if values_list is called with a single field > > branch_name = BranchModelChoiceField(branchqs) > > class Meta: > > model = Transaction > > fields = ('teller_no', 'paid') > > > Two things here. ModelChoiceField wants a real queryset, not a > ValuesQuerySet. The values of the model choice field should be the > primary keys of the model being chosen, which is not the case here > (which is why it fails). > > The second thing is that queryset is evaluated precisely once, when > the form is instantiated for the first time. When you add a branch, it > will not appear in that form until the server is restarted. > > Judging from your other reply, you don't actually want a foreign key > link to the branch, you simply want to store the name of the branch on > the transaction? If so, you should simply declare a ChoiceField and > supply it with choices derived from Branch. > > Eg: > > class TransactionUpdateForm(forms.ModelForm): > branch_name = ChoiceField(required=True) > def __init__(self, *args, **kwargs): > super(TransactionUpdateForm, self).__init__(*args, **kwargs) > self.fields['branch_name'].choices = > Branch.objects.all().values('name_branch', 'name_branch') > > Thanks for writing in Tom. I think what you did is the same as: class TransactionUpdateForm(forms.ModelForm): branchqs = Branch.objects.values_list('bid', u'name_branch') branch_name = BranchModelChoiceField(branchqs) I did try this earlier as well but didn't go to far with it. But then in the template file, I have {{form.branch_name}} which results into "Need more than 1 value to unpack error". How am I expected to print the form widget (select field) in a template? -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To post to this group, send email to [email protected]. > 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. > > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to [email protected]. 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.

