Reputation: 707
I'm trying to check if an object exists in my form but i'm getting an error.
my views:
def foo(request):
titulo = "something"
form = MyForm(request.POST or None)
queryset = myModel.objects.all()
if myModel.objects.filter(name=name).exists():
messages.error(request, 'already exists')
context = {
"titulo": titulo,
"form": form,
"queryset": queryset,
}
if form.is_valid():
instance = form.save()
messages.success(request, 'Added')
return redirect('/')
return render(request, "forms7.html", context)
Basically what I'm doing is adding an user, if the user exists I want a warning saying already exists
Error:
UnboundLocalError at /model/ local variable 'name' referenced before assignment
What am I doing wrong?
Note:
If I add name = 'jesus'
to my code and jesus
exists it works but that's not how I want.
I want to check if the name I'm entering exists show me the msg
Could someone help me? thanks.
Upvotes: 1
Views: 10899
Reputation: 15926
When using forms, you get an inputted form field by calling is_valid
and then accessing cleaned_data
, like this:
def foo(request):
titulo = "something"
form = MyForm(request.POST or None)
queryset = myModel.objects.all()
context = {
"titulo": titulo,
"form": form,
"queryset": queryset,
}
if form.is_valid():
name = form.cleaned_data['name']
if myModel.objects.filter(name=name).exists():
messages.error(request, 'already exists')
else:
instance = form.save()
messages.success(request, 'Added')
return redirect('/')
return render(request, "forms7.html", context)
Ideally, you’d have a clean_name
function in your form so that your view is less complicated. You can read more about creating such a method here.
For example, if you wanted to validate that the contents of a CharField called serialnumber was unique, clean_serialnumber() would be the right place to do this. You don’t need a specific field (it’s just a CharField), but you want a formfield-specific piece of validation and, possibly, cleaning/normalizing the data.
e.g., you might want something like:
class MyForm(forms.Form)
def clean_name(self):
name = self.cleaned_data['name']
if myModel.objects.filter(name=name).exists():
raise forms.ValidationError('The name [%s] already exists' % name)
return name
Upvotes: 5