简体   繁体   English

Django 1.9:将参数从urls.py传递到类视图

[英]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. 我正在创建一个小型Web应用程序,作为我的一个微型项目,以学习Django框架。 I'm on Version 1.9.4 , on OS X . 我使用的是OS X上的1.9.4版本 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. 我试图在URL中传递一个字符串,该字符串将被发送到基于类的视图,并且它将基于URL返回一个不同的模板。 To my knowledge, doing (?P) will allow the input of dynamic text. 据我所知,执行(?P)将允许输入动态文本。 \\w is for characters, and writing <name> will pass it as a variable. \\w用于字符,写<name>会将其作为变量传递。 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. 我担心的原因是Django文档使用方法视图,而我使用的是基于类的视图。

urls.py 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 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: 传递给url的参数应在相关函数内部的视图内“捕获”,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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