ViperStrike920
ViperStrike920

Reputation: 33

How to allow an empty foreign key in Django?

I'm very new to Django so this may be the dumbest question ever. I have 2 models set up in django; 'Class' and 'Profile'.

The 'Profile' class has a foreign key that references 'Class'. When creating a profile on the front end I am unable to leave the form blank as ("Profile.group" must be a "Class" instance.). I want to be able to create a profile that doesn't have to belong to a class.

class Class(models.Model):
    class_name = models.CharField(max_length=5)
    # a few other things that don't matter

    def __str__(self):
        return self.class_name

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # a few other things that don't matter
    group = models.ForeignKey(Class, on_delete=models.SET_NULL, null=True, blank=True)

and in form.py

class ProfileRegisterForm(forms.ModelForm):
    # a few other things
    group = forms.CharField(max_length=5, required=False)

If there is anything important that I've missed out please let me know, it's my first time posting here so I don't know what the standard is.

Upvotes: 2

Views: 549

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477035

I want to be able to create a profile that doesn't have to belong to a class.

That is already the case. By making the field nullable, you can just pass None to it, and then it does not relate to any class.

The group in your form however, should not be a CharField, but a ModelChoiceField. The way you communicate with the user is determined by the widget you attach to it. You can for example use a widget that implements a search bar, for example with django-select2 [Django-doc], or django-autocomplete-light [Django-doc]. django-autocomplete-lightweight allows to fetch the records through AJAX, making the burden on the render engine less.

For example we can install django-select2 in the virtual environment with:

pip install django_select2

Next in the ProfileRegisterForm we, can specifyh the widget as:

from django_select2.forms import Select2Widget
from app.models import Class

class ProfileRegisterForm(forms.ModelForm):
    group = forms.ModelChoiceField(
        queryset=Class.objects.all(), widget=Select2Widget
    )

    class Meta:
        model = Profile

Upvotes: 2

Related Questions