Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelChoiceField. ID instead of the name

Tags:

django

In send_option (in views) variable I have name of Send. I would like to have ID of Send

How to do it? Thanks

Form:

class SendOrderForm(forms.Form):
   send_option = forms.ModelChoiceField(queryset=Send.objects.all())

Model:

class Send(models.Model):
    name = models.CharField(max_length=50)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    time = models.CharField(max_length=150)

Views:

if request.method == 'POST':
        form = SendOrderForm(request.POST)
        if form.is_valid():
            send_option = form.cleaned_data['send_option']
like image 288
belisasun Avatar asked Oct 02 '12 11:10

belisasun


1 Answers

What you can do is,

if request.method == 'POST':
    form = SendOrderForm(request.POST)
    if form.is_valid():
        send_option = form.cleaned_data['send_option'].id

form.cleaned_data['send_option'] would get the object, and you can get its id by doing a .pk or .id

like image 60
karthikr Avatar answered Sep 28 '22 02:09

karthikr