【问题标题】:Django: issue with a simple formDjango:一个简单的表单问题
【发布时间】:2012-06-06 17:57:52
【问题描述】:

我是 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>

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多