2016-12-29 198 views
0

我試圖檢查一個對象是否存在於我的表單中,但是出現錯誤。Django - 檢查對象是否存在

我的看法:

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) 

基本上我做的是增加一個用戶,如果用戶存在,我想警告說already exists

錯誤:

UnboundLocalError at /model/ local variable 'name' referenced before assignment

我究竟做錯了什麼?

注: 如果我添加name = 'jesus'到我的代碼和jesus存在,它的工作原理,但是這不是我多麼希望。

我要檢查,如果我輸入名稱存在給我味精

有人能幫助我嗎?謝謝。

+3

哪裏變量'name'是從哪裏來的? –

回答

0

使用形式,可以通過調用is_valid,然後訪問cleaned_data,像這樣得到一個輸入表單字段:

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)  

理想情況下,你有一個clean_name功能在您的形式,使你的觀點是少複雜。你可以閱讀更多關於創建這樣的方法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.

例如,你可能想是這樣的:

class MyForm(forms.Form) 
    def clean_name(self): 
     name = self.cleaned_data['name'] 
     if myModel.objects.filter(name=name).exists(): 
      raise new forms.ValidationError('The name [%s] already exists' % name)  
     return name