Home > Software design >  In my Django project I have two similar url
In my Django project I have two similar url

Time:05-17

I have a question with my sites urls. When someone want to go mysite.com I redirect them to mysite.com/register.

url(r'^$', RedirectView.as_view(url='register/', permanent=False), name='index'),
url(r'^register/',views.guaform2,name='custform2'),

Also I have another url that allows to write somethings after the part of register. For example when someone goes to this website mysite.com/register/kh-54-m2-fc it allows to go that:

url(r'^register/(?P<pk>[-\w] )',views.guaform,name='custform'),

But when I use these urls together my guaform view doesn't work. And it goes to customer_form2.html. When someone goes this site: mysite.com/register/ anything I want them go to customer_form.html. How can I seperate these urls?

urls.py

from django.conf.urls import url
from django.contrib import admin
from olvapp import views
from django.views.generic import RedirectView

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', RedirectView.as_view(url='register/', permanent=False), name='index'),
    url(r'^register/',views.guaform2,name='custform2'),
    url(r'^register/(?P<pk>[-\w] )',views.guaform,name='custform'),

]

views.py

from django.shortcuts import render,HttpResponse
from olvapp.models import Customer
from olvapp.forms import CustomerForm,CustomerForm2
from django.conf import settings
from django.http import HttpResponseRedirect
from django.urls import reverse
from olvapp import forms

def guaform(request,pk):

    theurl = request.get_full_path()
    orderid = theurl[10:]

    form = CustomerForm(initial={'order_id':orderid})

    if request.method == "POST":
        form = CustomerForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect(reverse('thank'))
        else:

            HttpResponse("Error from invalid")

    return render(request,'customer_form.html',{'form':form})

def guaform2(request):
    form = CustomerForm2()

    if request.method == "POST":
        form = CustomerForm2(request.POST)

        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect(reverse('thank'))
        else:
            HttpResponse("Error from invalid")
    return render(request,'customer_form2.html',{'form':form})

CodePudding user response:

It should be enough to lock down the regular expression so it doesn't match in both cases.

Tighten the custform2 regex by using an dollar sign on the end to mark the end of the input:

url(r'^register/$',views.guaform2,name='custform2'),

That should be enough to get things working

  • Related