0

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

HahaMuntz
  • 45
  • 8
  • Maybe, you need this https://stackoverflow.com/a/252087/4723929 – A'zam Mamatmurodov Aug 08 '18 at 07:44
  • @A'zamMamatmurodov thanks for the answer, I saw that and to be honest I am not sure, if I understand it completely, but from what I understand he just found a way to limit the choices dynamically. That's not what I need, I am trying to change how the choices are displayed, but they are static. Please correct me if I understand it wrong. – HahaMuntz Aug 08 '18 at 08:07

0 Answers0