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

Cheers

Tom

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

Reply via email to