How do I filter Choice FK in Forms?
How do I filter Choice FK in Forms?
I want filter a choice in a form according user_logged. Here is my models.
#models.py
class Store(models.Model):
name = models.CharField(max_length=64, unique=True)
description = models.TextField(null=True, blank=True)
class StoreManager(models.Model):
store = models.ForeignKey(Store, related_name='store', on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
class StoreLogo(models.Model):
store = models.ForeignKey(Store, related_name='store', on_delete=models.CASCADE, verbose_name='Store')
image = photo = models.FileField()
First I created a Store, after that I Associate a StoreManager to a Store, and then I want in a forms add a ImageLogo, so in that forms, in field Store, I want list only a Store what user has associated.
Store = (SuperMarket Store), (ClothesStore)
StoreManager = John(SuperMarket Store), Julian(ClothesStore)
StoreLogo = John (can only view SuperMarket Sotre)
StoreLogo = Julian(can only view ClothesStore)
I'm using CBV(generic.CreateView).
There is my views.
#views.py
class AddPhotoOnEstablishment(LoginRequiredMixin, generic.CreateView):
model = StoreLogo
fields = ['store', 'image']
success_url = reverse_lazy('register:establishment_list')
context_object_name = 'object_name'
I want, if John has associated to Store and logged in the system, when he add a Image logo, the field Store only appear the Store he has associated.
1 Answer
1
maybe this link will help. it explained methods and attributes of CreateView class. in the render_to_response method you can get the current user using this code:
self.request.user
and check if it's associated with the store logo you're sending as response.
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.