two url one view - combining views

时间:2015-07-28 22:51:52

标签: python django twitter

I am attempting to build an app that can post tweet to a users twitter account from a text area (input by the user). I cannot though figure out how to include the textarea and the login/logout functionality within the same view (and thus called from the same urlpattern).

urls.py

url(r'^$', IndexView.as_view()),
url(r'^$','twitter_login.views.form_handle'),
#other url's omitted 

views.py

class IndexView(TemplateView):
    template_name = "index.html"

def log_out(request):
    logout(request)
    return redirect('/')

# cite karthikr: http://stackoverflow.com/questions/17754295/can-i-have-a-django-form-without-model
def form_handle(request):
    form = MyForm()
    if request.method=='POST':
    form = MyForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            text = cd.get('text')
            #functionality...
        return render(request, 'index.html',{'form':form}) 
    else:
        form = MyForm()
        return render(request, 'index.html',{'form':form})

Please may you show me how this can be done?

1 个答案:

答案 0 :(得分:0)

在Mathias给出了@login_required装饰器可以工作的答案后,我将它添加到窗体视图中,以便在views.py中显示:

from django.contrib.auth.decorators import login_required

@login_required
def form_handle(request):
    form = MyForm()
    #as above

运行此操作会出现错误"找不到页面(404)...当前的URL,accounts / login /,并不匹配其中任何一个。"所以我将IndexView的url模式更改为:

url(r'accounts/login/', IndexView.as_view())

现在它有效。这是一个hacky解决方案,我仍然不能完全理解TemplateView /视图如何交互的幕后情况,这将使我能够在未来构建更好的网站。所以,如果有人有更好的答案,我很乐意接受。

相关问题