Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django CreateView - Display only particular objects in foreignkey field

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!

like image 275
Quit3Simpl3 Avatar asked Nov 19 '17 10:11

Quit3Simpl3


Video Answer


1 Answers

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.

like image 90
user2390182 Avatar answered Sep 30 '22 17:09

user2390182