简体   繁体   中英

Django 1.9 : Passing arguments from urls.py to a class view

I am creating a small web application as a mini project of mine to learn the Django framework. I'm on Version 1.9.4 , on OS X . I'm trying to pass a string in the URL that will be sent to a class-based view, and it will return a different template based on the URL. To my knowledge, doing (?P) will allow the input of dynamic text. \\w is for characters, and writing <name> will pass it as a variable. Is this configured right, or is this is not the correct way to do it?

The reason I'm concerned is that the Django documentation uses method views, while I am using class-based views.

urls.py

from django.conf.urls import url
from . import views

app_name = 'xyz'

urlpatterns = [
    url(r'^create/(?P<ty>\w+)$', views.ArticleView.as_view(), name='article-form'),        #.as_view() to turn Class into View
]

views.py

class ArticleCreate(View):

  l = {
    'weapon': WeaponForm,
    'map': MapForm,
    'operator': OperatorForm,
    'gadget': GadgetForm,
    'skin': SkinForm
  }

  ty = ty.lower()

  template_name = 'xyz/create_article_form.html'

  def get(self, request):
    return render(request, self.template_name)

  def post(self, request):
    pass

The arguments that are being passed to the url should be "catched" within the view inside the relevant function, for example:

def get(self, request, ty):
    ty = ty.lower()
    return render(request, self.template_name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM