What I'm trying to achieve is give the currently logged in user the ability to add a product to a specific wishlist that the user has created earlier. To do this I want there to be a dropdown menu button with a list of all the current wishlists which the user has with a checkbox.
I have tried 2 ways to achieve this but none works as desired. What is the proper way to do this?
models.py
class Wishlist(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=50, null=True,blank=True)
slug = models.SlugField(max_length=50, null=True,blank=True)
wishlist_cover_image = models.ImageField(upload_to='media/WISHLIST_COVER_IMAGES/', null=True,blank=True)
description = RichTextField(max_length=500, null=True,blank=True)
products = models.ManyToManyField(Product, null=True,blank=True)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now_add=False ,null=True,blank=True)
def get_absolute_url(self):
return reverse('ecommerce:wishlist', args=[self.slug])
def __str__(self):
return self.title
With the below implementation I tried to do the user filtering with the traditional way by using "request.user" and got "request not defined" error.
forms.py
class AddToWishlistForm(forms.ModelForm):
wishlists = CustomWLMenu(queryset=Wishlist.objects.filter(user=request.user), widget=forms.CheckboxSelectMultiple)
class Meta:
model = Profile
fields = ['wishlists']
After looking around for a solution I came across the below method which retrieves all the wishlists rather than the currently logged in user like so:
forms.py
class CustomWLMenu(forms.ModelMultipleChoiceField):
def label_from_instance(self, user):
return "%s" % user
class AddToWishlistForm(forms.ModelForm):
wishlists = CustomWLMenu(queryset=Wishlist.objects.filter(), widget=forms.CheckboxSelectMultiple)
class Meta:
model = Profile
fields = ['wishlists']
