[Answered ]-How do you pass a Validation Error to html?

2👍

You have to do the validation error in forms;

class AddUserAccountsForm(forms.Form):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(AddUserAccountsForm, self).__init__(*args, **kwargs)


    def clean_name(self):
        Institution = Institution.objects.get(name=self.cleaned_data['name'])
        new_entry = User.objects.get(id=self.request.user.id)
        if Account.objects.filter(user=new_entry, institution=Institution.type).exists():
            raise forms.ValidationError(_('This account already exists'), code='invalid')
        return self.cleaned_data['name']

in views;

form = AddUserAccountsForm(request.POST, request=request)

0👍

@GeoJacob Thanks. To solve the user id issue, I used the following code:

def clean_name(self):
    Institution = Institution_long_tail.objects.get(name=self.cleaned_data['name'])
    current_user = wellfyUser.objects.get(id=self.instance.id)
    if Access_token_pair.objects.filter(user=current_user, institution=Institution.type).exists():
        raise forms.ValidationError(_('This account already exists'), code='invalid') 
    return self.cleaned_data['name']

with view:

form = AddUserAccountsForm(request.POST, instance=current_user)
👤H C

Leave a comment