6

I have a CreateView view that holds a bunch of fields that need to be filled by the user when creating a new contact. Now, I want the user to be able to see and choose only from the categories that they'd created. This is the model of Category:

class Category(models.Model):
    class Meta:
        verbose_name = _('category')
        verbose_name_plural = _('categories')

    name = models.CharField(max_length=100, unique=True)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)

    def __unicode__(self):
        return self.name

This is the view:

class ContactCreate(LoginRequiredMixin, generic.edit.CreateView):
    model = models.Contact
    success_url = reverse_lazy('site:contacts')
    fields = ['firstname', 'lastname', 'phone1', 'phone2', 'email', 'city', 'category']
    template_name = 'site/contacts.html'
    context_object_name = 'all_contacts'

What I need the user to see is a select that has only the categories which include the appropriate profile foreign key associated with them.

I'd be glad to get some help with this. Thank you!

Bubble Hacker
  • 6,425
  • 1
  • 17
  • 24
Quit3Simpl3
  • 183
  • 2
  • 14

1 Answers1

8

You can override the get_form method of the view and set the queryset of the appropriate field:

class ContactCreate(LoginRequiredMixin, generic.edit.CreateView):
    # ...
    def get_form(self, *args, **kwargs):
        form = super(ContactCreate, self).get_form(*args, **kwargs)
        form.fields['categories'].queryset = Category.objects.filter(profile=self.request.user.profile)
        return form

This, of course, assumes that your Profile model has a OneToOneField to User with related_name 'profile', otherwise you'd have to adjust the filtering.

user2390182
  • 72,016
  • 6
  • 67
  • 89