Django ModelForm提交到数据库

时间:2013-07-27 01:39:11

标签: python django views django-forms

当我将视图加载到:localhost:8000 / Scan时,会抛出以下问题:

TypeError on views.py in Scan, line 27:

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

知道我在这里做错了吗?我尝试过研究,但找不到答案。 (Django新手在这里)。谢谢大家!

Views.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

Forms.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()

3 个答案:

答案 0 :(得分: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方法中,您可以针对不同的条件引发异常。

答案 1 :(得分:0)

在request.method!=“POST”时失败,在这种情况下,表单未定义

答案 2 :(得分:-1)

问题不是django特有的,它是基本的python。你的缩进是错的。代码可能看起来像这样:

if request.method == 'POST':
    form = SubmitDomain(request.POST)
    if form.is_valid(): # indent fixed here
        form.cleaned_data['domainNm']