[Fixed]-How to raise forms validation error when ever the user try's to create an object with the object twice

1👍

You could do this by passing request.user into the form and use it for validating the canvas_name.

You need to override the form’s __init__ method to take an extra keyword argument, user. This stores the user in the form, where it’s required, and from where you can access it in your clean method.

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

def clean_canvas_name(self):
    canvas_name = self.cleaned_data.get('canvas_name')
    if Canvas.objects.get(user=self.user, canvas_name=canvas_name).exists():
        raise forms.ValidationError(u'Canvas with same name already exists.')
    return canvas_name

And you should change in your view like this so,

form_create = CanvasModelCreateForm(request.POST, user=request.user)

Leave a comment