I'm trying to add a choices
option to a ForeignKey
field. But that prevents the input form from getting validated.
I'm not sure if you can use choices
in ForeignKey
field, but how else would you provide human readable output for the choices?
I don't want the user to be able to choose from all groups and don't want to display the actual group name as it contains additional info for the admins, that shouldn't be visible to the user, for cosmetic reasons.
Any idea how to achieve that would be greatly appreciated.
Here is my code:
The model:
from django.contrib.auth.models import Group as DjangoGroup
class Category(models.Model):
created_by = models.ForeignKey('auth.User', on_delete=models.PROTECT, related_name='category_author')
last_edited_by = models.ForeignKey('auth.User', on_delete=models.PROTECT, related_name='category_editor')
name = models.CharField(max_length = 100)
privileges = models.ForeignKey('auth.Group', on_delete=models.PROTECT, blank=True, null=True, choices=((DjangoGroup.objects.get(pk=5), 'Test group'),))
The Form:
from django import forms
from .models import *
class CategoryForm(forms.ModelForm):
class Meta:
model = Category
exclude = ('created_by', 'last_edited_by',)
With this code the form gives the desired option 'Test group', but when I try to submit it I get the following error:
Select a valid choice. TestGroup(just for testing purposes) is not one of the available choices.
with 'TestGroup(just for testing purposes)' being the actual group name that I am trying to hide from the user.
I hope you can understand what I am trying to achieve. Am I on the right track or is there a different way to do this?
Thanks in advance for any answer