在表單提交後獲取Django身份驗證的“用戶”ID

2024-06-16 10:26:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前有一个模型表单,它向数据库提交输入的域。在

我遇到的问题是,我需要保存当前登录的用户ID(来自django.auth公司表)提交域以满足db端的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

而且视图.py

^{pr2}$

问题是给了我一个错误:(1048,“列'FKtoClient\uid'不能为空”),对于列FKtoClient,它试图提交:7L而不是{}(此用户记录的PK)。有什么想法吗?

如果有人能帮忙,我会非常感激的


Tags: django用户模型selfid数据库表单domain
3条回答

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

current_user = request.user

如果要要求用户登录以提交表单,可以执行以下操作:

@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()

首先,从表单中删除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的答案有一个优势,即如果需要,您可以在form方法中以self.instance.user的形式访问{}。在

相关问题 更多 >