0

I have a django model 'User' with a foreignkey to a related model 'Group'.

I am using a modelForm to render the form for creating a user, which allows the user to select a group from a dropdown of existing groups.

However, I'd like the option for the user to create a 'new' Group within that form if they don't find one they want in the list.

I know I could do an inline form, but I'm not sure how to accomplish that while retaining the ability to optionally select an existing related record.

Any advice?

corycorycory
  • 1,448
  • 2
  • 23
  • 42
  • 1
    it sound like you are searching for `get_or_create` method in Python. – hansTheFranz Jul 19 '17 at 15:33
  • Can you give me some guidance on how that would be used in a form? The group has a number of fields that would need to be provided if the user is creating a 'new' group. Whereas selecting an existing group the user would not need to enter any additional data. – corycorycory Jul 19 '17 at 16:05
  • https://stackoverflow.com/questions/22250352/in-django-how-do-you-programmatically-create-a-group-with-permissions how about this answer? it seems to include everything you want – hansTheFranz Jul 20 '17 at 11:33

1 Answers1

0

After many hours of rearch, I have found a solution.

I tried many things, including overriding the clean() function on my form, however that required removing immutability and was messy to get the validation right.

Ultimately my solution was so sublcasss ModelChoiceField. In the model choice field, override the to_python() method with your logic to create related object if it does not exist. In addition, I passed this field a queryset paramater so that in my form I was able to pass the newly created object only to this form instance, but not show on every users form.

class FlexibleModelChoiceField(ModelChoiceField):
    def __init__(self, queryset, *args, **kwargs):
        super(FlexibleModelChoiceField, self).__init__(queryset, *args, **kwargs)
        self.queryset = queryset

    def to_python(self, value):
        try:
            # Logic to get or create the model instance object
            return model_instance_object
        except (ValueError, self.queryset.model.DoesNotExist):
            raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
corycorycory
  • 1,448
  • 2
  • 23
  • 42
  • 2
    Could you please give a more elaborated code example and what goes in forms.py and what goes in views.py. I need to implement something same, but I am not able to understand from above example. – Ankita Nand Apr 28 '20 at 16:20