验证错误Django表单

时间:2014-11-07 20:38:58

标签: python django forms validation django-models

嘿所以我设置了一个输入表单,供用户在我在Django 1.5中开发的网站上分享他们正在处理的项目,我创建了模型,视图和表单模型,允许登录的用户添加链接他们正在进行的项目。

模型工作,当我通过管理面板输入文本时,它创建一个新对象,所有视图似乎都工作,表单加载,并且似乎接受输入但是,项目名称字段不断给我一个无效的输入当我尝试填写表单时出错,不知道为什么因为我输入了一个字符串,并且该字段在Model和Form Model中都被指定为CharField。

型号:

class Project(models.Model):
creator = models.ForeignKey(User)
project_name = models.CharField(max_length=128)
website = models.URLField(blank=True)
github = models.URLField(blank=True)
description = models.CharField(max_length=255, unique=True)
likes = models.IntegerField(default=0)

def __unicode__(self):

    return self.nam

添加项目的视图:

@login_required
def add_project(request):
context = RequestContext(request)

if request.method == 'POST':
    form = ProjectForm(request.POST)

    if form.is_valid():
        form.save(commit=False)
        project.creator = request.user
        project.save()


        return index(request)

    else:
        print form.errors
else:
    form = ProjectForm()

return render_to_response('rango/add_project.html', {'form' : form}, context)

表单模型:

class ProjectForm(forms.ModelForm):
project_name = forms.CharField(max_length=128, help_text="What is the name of your project?")
website = forms.CharField(max_length=200, help_text="Enter the project website:")
github = forms.CharField(max_length=200, help_text="Enter the project github:")
description = forms.CharField(widget=forms.Textarea, help_text="Description:")
likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)

class Meta:

    model = Project 

    exclude = ('creator')

def  clean(self):
    cleaned_data = self.cleaned_data
    website = cleaned_data.get('website')

    #If Url is not empty and dont start with 'http://' prepend 'http://'

    if website and not website.startswith('http://'):
        website = 'http://' + website
        cleaned_data['website'] = website

    return cleaned_data

def  clean(self):
    cleaned_data = self.cleaned_data
    github = cleaned_data.get('github')

    #If Url is not empty and dont start with 'http://' prepend 'http://'

    if github and not github.startswith('http://'):
        github = 'http://' + github
        cleaned_data['github'] = github

    return cleaned_data

最后是html模板:

{% extends 'rango/base.html' %}
{% block title %} Add Project {% endblock %}
{% block body_block %}
<H1>Add a new Project</H1>
<form id="project_form" method="post" action="/rango/add_project/">
    {% csrf_token %}
    {% for hidden  in form.hidden_fields %}
        {{hidden}}
    {% endfor %}
    {% for field in form.visible_fields %}
        {{field.errors}}
        {{field.help_text}}
        {{field}}
    {% endfor %}

    <input type="submit" name="submit" value="Create Project" />
</form>
{% endblock %}

页面加载正常,但是当我尝试提交时,我得到了项目名称:

输入有效值。

我输入的值是测试项目名称。

1 个答案:

答案 0 :(得分:0)

view函数中,我不明白project来自何处。

我希望相反:

project = form.save(commit=False)
project.creator = request.user
project.save()