Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7671341
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T16:01:45+00:00 2026-05-31T16:01:45+00:00

I have the following models: class Profile(models.Model): verified = models.BooleanField(default=False) primary_phone = models.OneToOneField(‘Phone’, related_name=’is_primary’,

  • 0

I have the following models:

class Profile(models.Model):
    verified = models.BooleanField(default=False)
    primary_phone = models.OneToOneField('Phone', related_name='is_primary', null=True, blank=True)

class Phone(models.Model):
    profile = models.ForeignKey(Profile)
    type = models.CharField(choices=PHONE_TYPES, max_length=16)
    number = models.CharField(max_length=32)

    @property
    def is_primary(self):
        return profile.primary_phone == self

And the following forms:

class PhoneForm(ModelForm):
    class Meta:
        from accounts.models import Phone
        model = Phone
        fields = ('type', 'number', )

which is being used in a modelformset_factory.

I’m rendering the formset like this:

<div class="span-13 last">
    {{ formset.management_form }}
    {% for form in Phones %}
        <div class="span-2">{{ form.type|add_class:'dropdown' }}</div>
        <div class="span-11 last">{{ form.number|add_class:'phone-number' }}</div>
        <div class="clearfix"></div>
    {% endfor %}
</div>

Now what I want to do is to render a radio button in the template to reflect the is_primary property of Phone model. There are two ways to determine this relationship, through Phone model itself or through Profile.primary_phone. But then I’m rendering Phone model as a formset, hence looping over its instances, so I tried to include 'is_primary' in PhoneForm fields, but it did not work since it’s a property.

Any idea how to do this?

UPDATE #1:

I have used jpic approach and tried to render primary as radio buttons:

class PhoneForm(ModelForm):
    primary = forms.BooleanField(widget=forms.RadioSelect( choices=((0, 'False'), (1, 'True')) ))

    class Meta:
        from accounts.models import Phone
        model = Phone
        fields = ('primary', 'type', 'number', )

However, it shows two radio buttons for each instance of Phone while I need it to show only one radio button per instance. I’m going to play around with it for a while and see if I can get it to show correctly.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T16:01:47+00:00Added an answer on May 31, 2026 at 4:01 pm

    Instead of:

    class Profile(models.Model):
        verified = models.BooleanField(default=False)
        primary_phone = models.OneToOneField('Phone', related_name='is_primary', null=True, blank=True)
    
    class Phone(models.Model):
        profile = models.ForeignKey(Profile)
        type = models.CharField(max_length=16)
        number = models.CharField(max_length=32)
    

    You should have:

    class Profile(models.Model):
        verified = models.BooleanField(default=False)
    
        def primary_phone(self):
            return self.phone_set.get(primary=True)
    
    class Phone(models.Model):
        profile = models.ForeignKey(Profile)
        type = models.CharField(max_length=16)
        number = models.CharField(max_length=32)
        primary = models.BooleanField(default=False)
    
        def save(self, force_insert=False, force_update=False, using=None):
            if self.primary:
                # clear the primary attribute of other phones of the related profile
                self.profile.phone_set.update(primary=False)
            self.save(force_insert, force_update, using)
    

    That would make your life easier.

    If you cannot make this change: a Phone formset is actually a wrapper around many Phone forms. But the field you’re after allows to edit Profile.primary_phone.

    So one way of doing it is to do it manually as such:

    {% for form in Phones %}
        <input type="radio" name="primary_phone" checked="{% if form.instance == profile.primary_phone %}checked{% endif %}" value="{{ form.instance.pk }}" />
        <!-- snip ... ->
    

    But the problem is that the radio won’t have a value for empty Phone forms, as the value is {{ form.instance.pk }}.

    Another way of doing it is to add a checkbox to PhoneForm:

    from django import forms
    
    from accounts.models import Phone
    
    class PhoneForm(forms.ModelForm):
        primary = forms.BooleanField(required=False, default=False)
    
        class Meta:
            model = Phone
            fields = ('type', 'number', )
    

    We’re using a BooleanField here because for each Phone form, primary is to be set or not. But still, you’ll have to render it yourself:

    {% for form in Phones %}
        <input type="checkbox" name="{{ form.prefix }}-primary" checked="{% if form.instance == profile.primary_phone %}checked{% endif %}" value="true" />
        <!-- snip ... ->
    

    But then, you need javascript to ensure only one radio is checked at the time, e.g. with jQuery:

    $('input[type=checkbox]').change(function() {
        $('input[type=checkbox][checked=checked]').attr('checked', '');
        $(this).attr('checked', 'checked');
    });
    

    Of course, you should update the selectors in this example above to ensure only “primary phone” checkboxes are affected.

    Finally, to connect the checkbox, something like this might work:

    class PhoneForm(forms.ModelForm):
        primary = forms.BooleanField(required=False)
    
        def __init__(self, *args, **kwargs):
            super(PhoneForm, self).__init__(*args, **kwargs)
    
            if self.instance.is_primary:
                self.data['primary'] = True
    
        def save(self, *args, **kwargs):
            super(PhoneForm, self).save(*args, **kwargs)
    
            if self.cleaned_data['primary']:
                self.profile.primary_phone = self
                self.profile.save()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following models (simplified): class Location(models.Model): name = models.CharField(max_length=100) is_ok = models.BooleanField()
I have following model: class UserProfile(models.Model): User profile model, cintains a Foreign Key, which
I have the following models: class UserProfile(models.Model): user = models.OneToOneField(User) score = models.PositiveIntegerField() class
I have the following models class Person(models.Model): name = models.CharField(max_length=100) class Employee(Person): job =
I have the following models: class City(models.Model): name = models.CharField(max_length=100) class Pizza(models.Model): name =
Suppose I have the following models: class User(models.Model): pass class A(models.Model): user = models.ForeignKey(User)
i have the following models setup class Player(models.Model): #slug = models.slugField(max_length=200) Player_Name = models.CharField(max_length=100)
I have the following abstract Django models: class Food(models.Model): name = models.CharField(max_length=100) class Meta:
Say I have the following in my models.py : class Company(models.Model): name = ...
I have the following models: class Application(models.Model): users = models.ManyToManyField(User, through='Permission') folder = models.ForeignKey(Folder)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.