表格没有通过

时间:2014-04-15 14:23:34

标签: python django python-2.7 django-forms

由于某种原因,我的表格没有通过。我还是django的新手。它应该显示在每个URL上,因此它位于base.html中,并且它有自己的应用程序;利益。它只是通过“添加”按钮,而不是形式.. :(

interest.html(包含在base.html中)

<form method='POST' action=''> {% csrf_token %}   
        <div class='row'>
        {{ interests_form.interest }}
        <input class='btn btn-success' type='submit' value='add'/>
        </div>
    </form> 

views.py

def user_interest(request):
    interest = Interests.objects.all()
    interests_form = InterestsForm(request.POST or None)

    if interests_form.is_valid():
        new_interest = interests_form.save(commit=False)
        new_interest.save()
        return HttpResponseRedirect('/')

    context = locals()
    return render(request, 'interest.html', context)

forms.py

class InterestsForm(forms.ModelForm):
    class Meta:
        model = Interests
        widgets = {
            'interest': forms.TextInput(attrs={'placeholder': 'New Interest'}),
        }

models.py

class Interests(models.Model):
    interest = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add=True)

urls.py

urlpatterns = patterns('',
    (r'^static/(?P<path>.*)$', 'django.views.static.serve', {
        'document_root': settings.STATIC_ROOT }), #needed for profile pic
    (r'^media/(?P<path>.*)$', 'django.views.static.serve', {
        'document_root': settings.MEDIA_ROOT }), #needed for profile pic
    url(r'^admin/', include(admin.site.urls)),
    (r'^accounts/', include('registration.backends.default.urls')),
    url(r'^$', 'profiles.views.base', name='home'),
    url(r'^users/$', 'profiles.views.all', name='users'),
    url(r'^about/$', 'about.views.about_us', name='about_us'), #the name is not needed in most cases
    url(r'^members/(?P<username>\w+)/$', 'profiles.views.single_user'),
    url(r'^edit/$', 'profiles.views.edit_profile', name='edit_profile'),
    (r'^edit/jobs$', 'profiles.views.edit_jobs'),
    (r'^edit/locations$', 'profiles.views.edit_locations'),
    url(r'^posts/$', 'posts.views.user_post', name='posts'), #change the middle section to: posts.views.'''
    url(r'^search/$', 'posts.views.search', name='search'),
)

2 个答案:

答案 0 :(得分:1)

@ {1}}视图未在urls.py中引用,也未在其他任何地方使用。里面的代码永远不会运行。

如果您想将user_interest添加到所有网页,您有两种主要方式:


例如,如果您选择编写上下文处理器,则应在应用程序的目录中创建interest_form文件并编写此简单处理器:

context_processors.py

然后,您需要将此功能添加到名为TEMPLATE_CONTEXT_PROCESSORS的设置中的上下文处理器列表中 - 类似于def user_interest(): interest = Interests.objects.all() interests_form = InterestsForm() return { 'interest': interest, 'interests_form': interests_form, }

这会使your_project.your_app.context_processors.user_interests查询集和interest表单在您的所有模板中都可用。您还需要在发送表单后添加单独的视图来处理表单。

答案 1 :(得分:0)

尝试按如下方式定义上下文变量:

context = (
'interests_form': interests_form,
)

也许值得尝试:

{{ interests_form.as_p }}

首先,查看渲染的HTML中是否有任何内容