0

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

我遇到的问题是,当提交域以满足 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,“列'FKtoClient_id'不能为空”),发生了非常奇怪的事情,对于列FKtoClient,它试图提交:7L而不是7(该用户记录的PK)。有任何想法吗?

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

4

3 回答 3

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

于 2013-10-31T15:58:01.957 回答
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()
于 2013-10-31T15:55:44.530 回答
0

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

current_user = request.user
于 2013-10-31T15:53:20.243 回答