Django:一个简单形式的问题

时间:2012-06-01 13:25:48

标签: django django-models django-forms django-templates django-views

我是django的新手,我遇到一个简单的表单POST问题。我在forms.py中有一个ModelForm,当用户在html中输入信息时,views.py会将其保存并保存。但是,我一直收到错误,说它无法找到view.py中不存在的视图。请帮我找错。谢谢!

urls.py

urlpatterns = patterns('',
                       (r'^mypage/(?P<username>\w+)/$', 'recipeapp.views.my_view'),

forms.py

class NewRecipeForm(forms.ModelForm):

    user_info = forms.ForeignKey(User)
    title = forms.CharField(min_length=2,max_length=50,required=True,)
    post_date = forms.DateField(auto_now=True)
    ingredients = forms.TextField(widget=forms.Textarea(),)
    picture = forms.ImageField(upload_to='photos/%Y/%m/%d',)
    content = forms.TextField(widget=forms.Textarea(),)

views.py

@csrf_protect
from recipeapp.forms import NewRecipeForm

    def my_view(request,username):
        if request.method == 'POST':
            form = NewRecipeForm(request.POST)
            if form.is_valid():
                form.save()
        else:
            form = NewRecipeForm()

        return render_to_response('postlogin.html',{'username':username},{'form': form}, RequestContext(request))

postlogin.html

        <form action="" method="post" id="form">
            {% csrf_token %}

                <div id="dish-name">
                <label><p>Dish name</p></label>
                {{form.title}}
                </div>

                <div id="ingredients">
                <label><p>Ingredients</p></label>
                {{form.ingredients}}
                </div>

                <div id="content">
                <label><p>Content</p></label>
                {{form.content}}
                </div>

                {{form.picture}}
       </form>

1 个答案:

答案 0 :(得分:1)

这真的是你的整个views.py吗?你至少有三个问题:

首先,你没有导入csrf_protect - 就像任何名字一样,需要先定义装饰器才能使用它。

其次,你必须装饰一个实际的功能,而不是文件。装饰器应该在my_view的函数定义之前。

第三,你的缩进被打破 - def根本不应缩进。

鉴于所有这些,我预计Python由于语法错误而无法导入您的视图。

另请注意,您不应该真正使用csrf_protect - 您应该在中间件中启用CSRF保护(默认情况下已启用)并且仅使用csrf_exempt装饰器,然后才会非常罕见场合。

相关问题