[英]Display URL in Lower Case in Django
My model has a category for a retailer--example - "Walmart" 我的模型为零售商指定了一个类别-例如-“沃尔玛”
All of the retailers in my database have been entered with the first letter capitalized. 我数据库中的所有零售商均已输入首字母大写。
I am trying to show a list of products by retailer on my site. 我试图在我的网站上显示零售商的产品列表。
My url looks like so: 我的网址看起来像这样:
path('retailer-deals/<str:retailer>', deals_by_retailer, name='retailer'),
and my view looks like this: 我的看法如下所示:
def deals_by_retailer(request,retailer):
retailer_deals = Deal.objects.filter(retailer__company=retailer).order_by('expired','-date_added')
retailer = retailer
return render(request, 'deals/deal_by_retailer.html', {'retailer_deals': retailer_deals, 'retailer': retailer})
So if i go to retailer-deals/walmart
nothing shows up... 因此,如果我去
retailer-deals/walmart
什么也没有出现...
but of course retailer-deals/Walmart
works fine 但是当然,
retailer-deals/Walmart
工作正常
i might be being nitpicky--but i think it looks more professional with the lower case walmart
and just in case someone goes to enter the uppercase version, i want to make sure it populates correctly 我可能很挑剔-但我认为小写的
walmart
看起来更专业,以防万一有人输入大写的版本,我想确保它能正确填充
I did see someone mention a (?i) for a similar problem, 我确实看到有人提到(?i)类似问题,
and i tried changing my path to this: 我试图改变我的道路:
path('(?i)retailer-deals/<str:retailer>', deals_by_retailer, name='retailer'),
but that doesn't seem to work....and also, if i go to list the retailers with associated links--the generated url will still have the uppercase url.. 但这似乎不起作用....而且,如果我用相关链接列出零售商,则生成的url仍将包含大写url。
You can use iexact in your filter, A case-insensitive exact match. 您可以在过滤器中使用iexact ,不区分大小写的完全匹配。
retailer_deals = Deal.objects.filter(
field_name__iexact=retailer).order_by('expired','-date_added')
As many of other people suggest, the best way is to do such query with slug, so you would have: 正如其他许多人所建议的那样,最好的方法是使用slug进行此类查询,因此您将:
from django.template.defaultfilters import slugify
import uuid
class YourModel(mdoels):
slug = models.SlugField()
name = models.CharField(max_mength=100)
# override the save method to have slug automatically generated
def save(self, *args, **kwargs):
if self.pk is None:
slug = slugify(self.name)
while self.__class__.objects.filter(slug=slug).exists():
slug = "%s-%s" % (slug,str(uuid.uuid4())[:5])
self.slug = slug
super(YourModel, self).save(*args, **kwargs)
your url would become: 您的网址将变为:
path('retailer-deals/<slug:slug>', deals_by_retailer, name='retailer'),
and your views: 和您的意见:
def deals_by_retailer(request,slug):
retailer_deals = Deal.objects.filter(retailer__slug=slug)
''' codes '''
I'm going to answer your question indirectly because I think doing an iexact
filter in your routes is a code smell. 我将间接回答您的问题,因为我认为在路由中执行
iexact
过滤器会产生代码异味。 It also opens you up to people typing paths like retailer-deals/WaLmArT
which would then break if you switched to a setup with slugs down the road for simplicity. 它还为您打开了键入
retailer-deals/WaLmArT
类的路径的retailer-deals/WaLmArT
,如果您切换到一条retailer-deals/WaLmArT
的安装程序(为简单起见),该路径就会中断。
The best practice is to use slugs to define URLs for longevity. 最佳做法是使用段来定义URL以延长使用寿命。 Things like spaces, punctuation, and non-ASCII character encoding used in names can make for ugly or invalid URLs.
名称中使用空格,标点符号和非ASCII字符编码之类的内容可能会造成难看或无效的URL。
You can use a slug in urlpatterns
like: 您可以在
urlpatterns
使用slug:
from django.urls import path
from . import views
urlpatterns = [
...
path('widgets/<slug:slug>/', views.foo),
]
There's more info in the docs for this example. 在此示例的文档中有更多信息。
Django has a built-in SlugField model field for this use case. Django在此用例中具有内置的SlugField模型字段。 You can also prepopulate it in the Django admin from another field such as title.
您还可以在Django管理员中从另一个字段(例如title) 预填充它 。
class WidgetAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
Your path is find. 找到你的路。
path('retailer-deals/<str:retailer>', deals_by_retailer, name='retailer'),
your <str:retailer>
is some arguments that your request get. 您的
<str:retailer>
是您的请求得到的一些参数。
It means it's not fix one. 这意味着它不是固定的。 You can attach anything you want - like
pk
, slug
, title
, uuid
and so on. 您可以附加任何想要的东西-如
pk
, slug
, title
, uuid
等等。
So In your situation, if you want to use lowercase in your url, you can add your own slug to your model, and pass it to your url. 因此,根据您的情况,如果要在URL中使用小写字母,可以将自己的Slug添加到模型中,并将其传递给URL。
ie 即
Your urls will be 您的网址将是
path('retailer-deals/<str:slug>', deals_by_retailer, name='retailer'),
And your views will be 您的意见将是
def deals_by_retailer(request,slug):
retailer_deals = Deal.objects.filter(retailer__slug=slug).order_by('expired','-date_added')
retailer = retailer
return render(request, 'deals/deal_by_retailer.html', {'retailer_deals': retailer_deals, 'retailer': retailer})
Also you have to add slug to your model 另外,您还必须向模型添加块
# maybe your Retailer model
Retailter(models.Model):
...
slug = models.CharField(
max_length=100,
verbose_name="slug",
)
...
# You can save slug automaticall when saving
# using __save__ or signals
Using slug in url is good way for many reasons (url not support white space, and many other chars, but your
company
fields can get them).出于多种原因,在url中使用slug是一种好方法(url不支持空格和许多其他字符,但是您
company
字段可以获取它们)。 So you can make slug from your company - unique and well-fit to url.因此,您可以从您的公司中获得产品-独特且非常适合url。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.