2013-10-31 28 views
0

我目前有一個模型表單,將輸入的域提交給數據庫。在表單提交時獲取Django Auth「用戶」標識

我遇到的問題是,我需要保存當前登錄的用戶的ID(從django.auth表中PK),當提交一個域以滿足數據庫端的PK-FK關係時。

我目前有:

class SubmitDomain(ModelForm): 
    domainNm = forms.CharField(initial=u'Enter your domain', label='') 
    FKtoClient = User.<something> 

    class Meta: 
     model = Tld #Create form based off Model for Tld 
     fields = ['domainNm'] 

def clean_domainNm(self): 
    cleanedDomainName = self.cleaned_data.get('domainNm') 
    if Tld.objects.filter(domainNm=cleanedDomainName).exists(): 
     errorMsg = u"Sorry that domain is not available." 
     raise ValidationError(errorMsg) 
    else: 
     return cleanedDomainName 

views.py

def AccountHome(request): 
    if request.user.is_anonymous(): 
     return HttpResponseRedirect('/Login/') 

    form = SubmitDomain(request.POST or None) # A form bound to the POST data 

    if request.method == 'POST': # If the form has been submitted... 
     if form.is_valid(): # If form input passes initial validation... 
      domainNmCleaned = form.cleaned_data['domainNm'] ## clean data in dictionary 
      clientFKId = request.user.id 
      form.save() #save cleaned data to the db from dictionary` 

      try: 
       return HttpResponseRedirect('/Processscan/?domainNm=' + domainNmCleaned) 
      except: 
       raise ValidationError(('Invalid request'), code='300') ## [ TODO ]: add a custom error page here. 
    else: 
     form = SubmitDomain() 

    tld_set = request.user.tld_set.all() 

    return render(request, 'VA/account/accounthome.html', { 
     'tld_set':tld_set, 'form' : form 
    }) 

問題是,它給我的錯誤:(1048,「列FKtoClient_id'不能爲空「),非常奇怪的事情發生,對於列FKtoClient,它試圖提交:7L而不是7(此用戶的記錄的PK)。有任何想法嗎?

如果有人能請大家幫忙,我真的很感激它

+1

不要擔心'7L',請參閱[這個問題](http://stackoverflow.com/questions/11764713/why-do-integers-in-database-row-tuple-have-an-l-後綴)以獲取更多信息。 – Alasdair

回答

2

首先,從表單中刪除FKtoClient。您需要在視圖中設置用戶,您可以將請求對象設置爲yes。無法在自動設置當前用戶的表單上設置屬性。

當實例化表單時,您可以傳遞已有用戶設置的tld實例。

def AccountHome(request): 
    # I recommend using the login required decorator instead but this is ok 
    if request.user.is_anonymous(): 
     return HttpResponseRedirect('/Login/') 

    # create a tld instance for the form, with the user set 
    tld = Tld(FKtoClient=request.user) 
    form = SubmitDomain(data=request.POST or None, instance=tld) # A form bound to the POST data, using the tld instance 

    if request.method == 'POST': # If the form has been submitted... 
     if form.is_valid(): # If form input passes initial validation... 
      domainNm = form.cleaned_data['domainNm'] 
      form.save() #save cleaned data to the db from dictionary 

      # don't use a try..except block here, it shouldn't raise an exception 
      return HttpResponseRedirect('/Processscan/?domainNm=%s' % domainNm) 
    # No need to create another form here, because you are using the request.POST or None trick 
    # else: 
    # form = SubmitDomain() 

    tld_set = request.user.tld_set.all() 

    return render(request, 'VA/account/accounthome.html', { 
     'tld_set':tld_set, 'form' : form 
    }) 

這個擁有@ dm03514的答案,這是你可以在需要的形式方法爲self.instance.user內訪問user的優勢。

+0

如何在我的代碼中實現此功能以獲取用戶標識? – CodeTalk

+0

我不明白你的問題。我上面的例子將'tld.user'設置爲發出請求的用戶。如果你想訪問用戶ID,使用'request.user.id'。沒有辦法在窗體類上聲明'FKtoClient',並讓它在當前請求中用用戶神奇地更新窗體。要訪問用戶,你必須在視圖(或適當的模型管理方法)中訪問'request.user',然後更新設置窗體或實例。 – Alasdair

+0

您能否使用request.user.id顯示一個使用示例? – CodeTalk

0

你可以得到登陸用戶從請求對象:

current_user = request.user 
+0

但是,如何從django auth用戶表中獲取用戶的ID?用戶已經正確認證。 – CodeTalk

+0

request.user.id? – Ogre

+0

這可以用在forms.py中嗎?它需要哪些進口? – CodeTalk

1

如果你想要求用戶在登錄提交表單,你可以這樣做:

@login_required # if a user iS REQUIRED to be logged in to save a form 
def your_view(request): 
    form = SubmitDomain(request.POST) 
    if form.is_valid(): 
    new_submit = form.save(commit=False) 
    new_submit.your_user_field = request.user 
    new_submit.save() 
+0

這不是要求。用戶已經通過身份驗證。他/她提交表格並在提交時目前提交表格條目,但還必須包括已登錄用戶的ID。那有意義嗎? – CodeTalk

+0

本示例視圖向您展示瞭如何在保存表單時設置用戶。你應該能夠調整你的觀點來做同樣的事情。如果你試圖在Django管理員而不是視圖中這樣做,你應該更新你的問題來說明。 – Alasdair

相關問題