【问题标题】:Get Django Auth "User" id upon Form Submission提交表单时获取 Django Auth“用户”ID
【发布时间】:2013-10-31 15:45:49
【问题描述】:

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

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

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)。有什么想法吗?

如果有人可以帮忙,我将不胜感激

【问题讨论】:

标签: python django primary-key django-forms


【解决方案1】:

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

【讨论】:

  • 我不明白你的问题。我上面的示例将tld.user 设置为发出请求的用户。如果要访问用户 ID,请使用 request.user.id。没有办法在表单类上声明FKtoClient,并让它神奇地更新当前请求中的用户表单。要访问用户,您必须在视图(或合适的模型管理方法)中访问request.user,然后更新设置表单或实例。
  • 能否展示一个使用 request.user.id 的示例?
  • 我不能再帮你了,因为我不明白你在做什么。如果您希望将tld.user 字段设置为当前用户,那么我的示例将起作用。
  • 正如问题所述:我只是想从 Django Auth“用户”表中获取当前经过身份验证的用户(id)。用户表中的每条记录都有一个与名为“id”的列关联的主键。这有意义吗?
  • 它不是库,它是视图中的request 对象。我和@dm03514 都已经为您提供了一些视图示例,这些视图可以满足您的需求。
【解决方案2】:

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

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

【讨论】:

  • 这不是要求。用户已通过身份验证。他/她正在提交一个表单,并且在提交时它当前提交表单条目,但它还必须包含已登录用户的 id。这有意义吗?
  • 此示例视图向您展示了如何在保存表单时设置用户。你应该能够调整你的视图来做同样的事情。如果您尝试在 Django 管理员而不是视图中执行此操作,则应更新您的问题以说明这一点。
【解决方案3】:

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

current_user = request.user

【讨论】:

  • 但是,如何从 django auth User 表中获取用户 ID?用户已通过正确身份验证。
  • 可以在forms.py中使用吗?它需要哪些进口?
猜你喜欢
  • 2017-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-04
  • 1970-01-01
  • 2014-03-29
  • 1970-01-01
  • 2016-05-05
相关资源
最近更新 更多