在表单提交时获取Django Auth“用户”ID

时间:2013-10-31 15:45:49

标签: python django primary-key django-forms

我目前有一个模型表单,可以将输入的域提交给数据库。

我遇到的问题是,当提交域以满足db端的PK-FK关系时,我需要保存当前登录用户的ID(来自django.auth表的PK)。

我目前有:

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,“Column'FKtoClient_id'不能为空”),非常奇怪的事情,对于列FKtoClient,它试图提交:{ {1}}而不是7L(此用户记录的PK)。有什么想法吗?

如果有人可以请求帮助,我会非常感激

3 个答案:

答案 0 :(得分:2)

首先,从表单中删除FKtoClient。您需要在视图中设置用户可以使用请求对象的用户。无法在自动设置当前用户的表单上设置属性。

在实例化表单时,您可以传递已经设置了用户的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的答案更有优势,即如果需要,您可以在表单方法中访问user self.instance.user

答案 1 :(得分: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()

答案 2 :(得分:0)

您可以从请求对象中获取登录用户:

current_user = request.user