如何在django中创建url

时间:2016-03-28 18:18:18

标签: python django

我制作这个django程序,我有登录页面,注册页面,用户登录后我有一个按钮“创建处方”。我的问题是它不起作用。

这是urls.py

from django.conf.urls import patterns, include, url
from createprescription.views import *
from . import views

urlpatterns = patterns('',
    url(r'^$', 'django.contrib.auth.views.login'),
    url(r'^logout/$', logout_page),
    url(r'^accounts/login/$', 'django.contrib.auth.views.login'), # If user is not login it will redirect to login page
    url(r'^register/$', register),
    url(r'^register/success/$', register_success),
    url(r'^home/$', home),
    url(r'^$', views.createprescription, name='createprescription'),
    )

这来自views.py

from createprescription.forms import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext


@csrf_protect
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
            username=form.cleaned_data['username'],
            password=form.cleaned_data['password1'],
            email=form.cleaned_data['email']
            )
            return HttpResponseRedirect('/register/success/')
    else:
    form = RegistrationForm()
    variables = RequestContext(request, {
    'form': form
    })

    return render_to_response(
    'registration/register.html',
    variables,
    )

def register_success(request):
    return render_to_response(
    'registration/success.html',
    )

def logout_page(request):
    logout(request)
    return HttpResponseRedirect('/')

@login_required
def home(request):
    return render_to_response(
    'home.html',
    { 'user': request.user }
    )

def createprescription(request):
    return render(request, 'createprescription/createprescription.html', {})       

这就是错误:

Using the URLconf defined in cwbis.urls, Django tried these URL patterns, in this order:

    ^admin/
    ^$
    ^logout/$
    ^accounts/login/$
    ^register/$
    ^register/success/$
    ^home/$
    ^$ [name='createprescription']

The current URL, createprescription, didn't match any of these.

1 个答案:

答案 0 :(得分:0)

您正试图强制登录您的主页,但这不是实现它的方式。这两个URL是冲突的,系统将只使用第一个:

url(r'^$', 'django.contrib.auth.views.login'),
url(r'^$', views.createprescription, name='createprescription'),

要解决错误,您应该删除行

url(r'^$', 'django.contrib.auth.views.login'),
来自urls.py

为了仅允许登录用户查看您的处方页,请在views.py添加以下行:

from django.contrib.auth.decorators import login_required
...
@login_required
def createprescription(request):
    ...