3๐
โ
-
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
-
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
Source:stackexchange.com