[Django]-Django โ€“ prevent duplicates for users

3๐Ÿ‘

โœ…

  1. Pass user to form โ€“ add him to form kwargs by adding this method to view:

    def get_form_kwargs(self, *args, **kwargs):
        kwargs = super(Create, self).get_form_kwargs(*args, **kwargs)
        kwargs['user'] = self.request.user
        return kwargs
    
  2. Get user in form and check:

    def __init__(self,*args, **kwargs):
        self.user = kwargs.pop('user') # this line added
        super(AlbumCreateForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget = forms.TextInput(
           attrs={'placeholder': 'name'})
    
    def clean(self):
        if Album.objects.filter(user=self.user).exists():
            raise forms.ValidationError('Error description')
    
๐Ÿ‘คzymud

Leave a comment