Hello all,

Is there a way to have a foreign key on a model which uses a type other than
Django's forceful
int type to make the storage for a ModelChoiceField widget?

I have something like this I'm working with:

forms.py
------------

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

models.py
--------------
class Branch(models.Model):
    """ Branch """
    bid = models.AutoField(primary_key=True)
    name_branch = models.CharField(max_length=255)

    class Meta:
        db_table = u'branch'

    def __unicode__(self):
        return self.name_branch

class Transaction(models.Model):
    id = models.AutoField(primary_key=True)
    branch_name = models.ForeignKey(Branch, blank=True, null=True,
related_name='transaction')
    paid = models.BooleanField(default=False)
    teller_no = models.CharField(max_length=20, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

in views.py
---------------
if request.POST:
        update_form = TransactionUpdateForm(request.POST, instance=txn)
        txn.branch_name = Branch([int(k) for k,v in dic.iteritems() if v ==
update_form.cleaned_data['branch_name']][0]) # Forcefully store the key
        if update_form.is_valid():
            update_form.save()

The form worked perfectly in admin but not from my own custom ModelForm.

I don't know if my title is correct as I can see that Django saves the
selected element key in
the db and not its value which will be of type integer

I'm getting the error from my oen custom ModelForm:
<ul class="errorlist"><li>branch_name<ul class="errorlist"><li>Select a
valid choice.
 That choice is not one of the available choices.</li></ul></li></ul>

Please how do I get the form saved with the selected branch value?

Please help.

Thanks

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

Reply via email to