在Django中,可以使用相同的urlpattern指定单独的`http`动词吗?

时间:2018-09-09 17:24:54

标签: python django django-urls

我正在Django 2.1中创建注册表。在典型示例中,人们使用相同的views方法显示表单并接受来自以下表单的POST请求:

urls.py中:

urlpatterns = [
    path('auth/register', auth.register, name='register')
]

并在名为auth.py的视图中:

from django.shortcuts import render
from blog_admin.forms import SignUpForm
from django.contrib.auth.forms import UserCreationForm


def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            # do registration stuff...
    else:
        form = SignUpForm()

        return render(request, 'blog_admin/auth/register.html', {'form': form})

但是我想使用单独的方法来显示表单和处理注册过程,并且还想使用相同的urlpatterns功能和GET,以及功能POST,如下所示:< / p>

urls.py

    urlpatterns = [
        # can we limit it range, so that it only works for GET request
        path('auth/register', auth.show_registration_form, name='register_show'),
        # can we limit it range, so that it only works for POST request
        path('auth/register', auth.register, name='register')
    ]

并在名为auth.py的视图中:

from django.shortcuts import render
from blog_admin.forms import SignUpForm
from django.contrib.auth.forms import UserCreationForm


def show_registration_form(request):
    form = SignUpForm()

    return render(request, 'blog_admin/auth/register.html', {'form': form})

def register(request):
    # do registration stuff...

如果需要其他框架的更多示例,请在php Laravel中执行以下操作:

Route::get('auth/register', ['as' => 'register_show', 'uses' => 'Auth\AuthController@show_registration_form']);
Route::post('auth/register', ['as' => 'register', 'uses' => 'Auth\AuthController@register']);

0 个答案:

没有答案