2015-05-12 70 views
0

我開始使用UserCreationForm的Django應用程序,用戶默認的Django應用程序。它在mysql中創建一個表,然後你就可以創建新的用戶。但我需要的是將用戶與MySQL中現有的數據庫進行比較。我如何指定UserCreationForm必須查找用戶的數據庫? 我的主視圖與字段填寫登錄:如何實現Django'UserCreationForm'從現有的mysql數據庫中檢查用戶?

def mainview(request): 
    if not request.user.is_anonymous(): 
     return HttpResponseRedirect('/private') 
    if request.method == 'POST': 
     formulario = AuthenticationForm(request.POST) 
     if formulario.is_valid: 
      usuario = request.POST['username'] 
      clave = request.POST['password'] 

      acceso = authenticate(username=usuario, password=clave) 
      if acceso is not None: 
       if acceso.is_active: 
        login(request, acceso) 
        return HttpResponseRedirect('/privado') 
       else: 
        return render_to_response('noactivo.html', context_instance=RequestContext(request)) 
      else: 
       return render_to_response('nousuario.html', context_instance=RequestContext(request)) 
    else: 
     formulario = AuthenticationForm() 
    return render_to_response('mainview.html',{'formulario':formulario}, context_instance=RequestContext(request)) 
+0

https://docs.djangoproject.com/en/1.8/ref/settings/#databases – Anentropic

+0

的問題是,當你配置這樣的Django數據庫中創建自己的表。我需要在由移動應用程序共享的另一個現有數據庫中查找用戶。 –

+1

https://docs.djangoproject.com/en/1.8/howto/legacy-databases/ – Anentropic

回答

2

兩種方法可以做到這一點,創建自己的用戶模型,使用戶名唯一的,但最簡單的方法;繼承UserCreationForm並添加clean_username函數。

因此,像:

class MyUserCreationForm(UserCreationForm): 
    def clean_username(self): 
     username = self.cleaned_data["username"] 
     if User.objects.filter(username=username).exists(): 
      raise forms.ValidationError("Username already exists") 
     # return is not required Django 1.7 and up, but do it anyway 
     return username 

====更新後評論==== 有兩個數據庫,所以你需要設置(https://docs.djangoproject.com/en/1.8/ref/settings/#databases)中添加第二個數據庫。 可以說你給第二個數據庫的用戶名命名。現在又有兩個選項。第一個選擇是,使用遊標進行原始SQL(https://docs.djangoproject.com/en/1.8/topics/db/sql/#executing-custom-sql-directly)。

from django.db import connections 
cursor = connections['usernames'].cursor() 

第二個選項是創建一個與當前表具有相同設計的模型。使用上述表單,但在查詢集上使用using。因此,像這樣:

if YourModel.objects.using('usernames').filter(username=username).exists(): 
    raise forms.ValidationError("Username already exists") 
+0

謝謝,我會去嘗試這個選項 –

+0

但我的問題仍然是一樣的。我想在不同的和現有的MySQL表中查找用戶名,而不是Django創建的用戶名。 –

+0

Oké,我會調整我的答案 – Blackeagle52

相關問題