0

当我在 localhost:8000/Scan 加载视图时,它会引发以下问题:

TypeError on views.py in Scan, line 27:

form = Scan() # Otherwise, set the form to unbound

知道我在这里做错了什么吗?我尝试研究,但找不到答案。(这里是 Django 新手)。谢谢你们!

视图.py

from django.http import HttpResponse
from Scanner.forms import SubmitDomain

def Scan(request):
    if request.method == 'POST': # If the form has been submitted...
        form = SubmitDomain(request.POST) # A form bound to the POST data
    if form.is_valid(): # If form input passes initial validation...
        form.cleaned_data['domainNm']  ## clean data in dictionary
        try:
            ## check if Tld Table has submitted domain already
            from Scanner.models import Tld
            Tld.objects.get(domainNm=form.cleaned_data['domainNm'])

        except Tld.DoesNotExist:
            print "Would you like to create an account?"
            ## redirect to account creation

        else:
            print "Do you have an account? Please login."
            ## redirect to account login

    else:
        form = Scan() # Otherwise, set the form to unbound

表格.py

from django.forms import ModelForm
from Scanner.models import Tld

class SubmitDomain(ModelForm):

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

    def clean_domainName(self):
        val = self.clean_domainName('domainNm')
        return val

## This creates the form.
form = SubmitDomain()
4

3 回答 3

1

在您的模型形式中:

from django.forms import ModelForm
from Scanner.models import Tld

class SubmitDomainForm(ModelForm):
    class Meta:
        model = Tld
        fields = ['domainNm']

    def clean_domainName(self):
        val = self.cleaned_data.get('domainNm')
        if Tld.objects.filter(domainNm=val).count() > 0:
            raise forms.ValidationError(u'Sorry that domain already
                exists, etc, etc')
        return val

在您看来,请执行以下操作:

from django.shortcuts import render
from Scanner.forms import SubmitDomainForm

def scan(request):  # functions should start with a lowercase letter
    # Bind the post data to the form, if it exists.
    # No need for a separate if statement here
    form = SubmitDomainForm(request.POST or None)

    if request.method == 'POST':
        if form.is_valid():
            # save your model form, or do something else

    return render(request, 'your-template.html', {'form': form})

希望对您有所帮助。您的视图当前正在为表单实例化错误类型的对象,因此出现 TypeError。您当前在模型表单上的 clean 方法将永远不会验证任何内容。它只是将值设置为等于 clean 函数。与其用表单验证逻辑使您的视图混乱,不如将其放入该字段的表单的 clean 方法中,您可以针对不同的条件引发异常。

于 2013-07-27T01:52:53.680 回答
0

当 reuqest.method != "POST" 时失败,在这种情况下未定义表单

于 2013-07-27T01:49:43.860 回答
-1

问题不是特定于 django,它是基本的 python。你的缩进是错误的。代码应该如下所示:

if request.method == 'POST':
    form = SubmitDomain(request.POST)
    if form.is_valid(): # indent fixed here
        form.cleaned_data['domainNm'] 
于 2013-07-27T01:48:47.783 回答