ModelMultipleChoisefield with unique objects from each user Django

0

I have a user model that has a ManytoMany () field to another object:

class PrivateWallet(models.Model):
    name = ...

class Usuario(AbstractUser):
    private_wallets = models.ManyToManyField(PrivateWallet, blank=True)

and I want to create a form in which the user can delete that PrivateWallet:

class DeletePrivateWalletForm(forms.Form):
    wallets = ModelMultipleChoiceField(queryset=¿?.objects.all(),to_field_name="name",required=True)

I would like to know what I have to put in place of ¿? of the form so that the user is shown only the privateWallets created by him.

    
asked by XBoss 14.07.2018 в 22:27
source

1 answer

1

For what you want to do the best is to modify the field from the constructor of the class, passing to the constructor as argument the user or queryset from which the wallets will be displayed. In this way:

class DeletePrivateWalletForm(forms.Form):
    wallets = ModelMultipleChoiceField(queryset=PrivateWallet.objects.none(), to_field_name="name", required=True)

    def __init__(self, *args, **kwargs):
        user = kwargs.get('user', None)
        super().__init__(*args, **kwargs)
        if user is not None:
            self.fields['wallets'].queryset = user.private_wallets.all()

And in your view, when you are going to create the instance of the form, remember to pass the user, for example:

def view(request):
    if request.method == 'POST':
        form = DeletePrivateWalletForm(data=request.POST, user=request.user)
        if form.is_valid():
            ...
    else:
        form = DeletePrivateWalletForm(user=request.user)
    return render...
    
answered by 16.07.2018 / 17:12
source