SyntaxError
SyntaxError

Reputation: 23

How can I get user selected radio option? Django

I have a model named UserAddress and a form created from the same model which is UserAddressForm.

class UserAddress(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    address = models.CharField(max_length=120)
    address2 = models.CharField(max_length=120, null=True, blank=True)
    city =  models.CharField(max_length=120, null=True, blank=True)
    phone =  models.CharField(max_length=120)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return self.get_address()
    def get_address(self):
        return"%s,%s,%s,%s" %(self.address, self.address2,self.city,self.phone)

I am displaying all the user addresses in the html with a radio check-box. I want to get the user selected address in my view and assign to another model instance which I am unable to figure out. How can I do this?

Upvotes: 1

Views: 471

Answers (1)

Yuri Kriachko
Yuri Kriachko

Reputation: 294

If your models structure is following:

class UserAddress(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    address = models.CharField(max_length=120)
    address2 = models.CharField(max_length=120, null=True, blank=True)
    city =  models.CharField(max_length=120, null=True, blank=True)
    phone =  models.CharField(max_length=120)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return self.get_address()
    def get_address(self):
        return"%s,%s,%s,%s" %(self.address, self.address2,self.city,self.phone)


class Order(models.Model):
    address = models.ForeignKey(UserAddress)

You can make a form based on Order model, put ModelChoiceField and specify widget to be RadioSelect

from django import forms


class OrderForm(forms.Form):
    address = forms.ModelChoiceField(
        queryset=UserAddress.objects.all(),
        widget=forms.widgets.RadioSelect(),
    )

In that case when you handle OrderForm submit you will have address which user is choose.

Upvotes: 1

Related Questions