问题描述
我已经看到了各种不同的方法来产生独特的s s声:,,,等等。
我想在保存ModelForm时创建独特的s。。如果我的模型如下所示:
class Phone(models.Model):
user = models.ForeignKey(User)
slug = models.SlugField(max_length = 70,unique = True)
year = models.IntegerField()
model = models.ForeignKey('Model')
series = models请问这个$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ c> object具有以下值(通过提交的ModelForm): Phone.user = dude
Phone.year = 2008
Phone.model = iphone
Phone.series = 4S
我希望此对象的网址显示为:
http://www.mysite.com/phones/dude-2008- iphone-4S
我明白我应该使用 slugify
通过信号或超越保存方法来实现这一点。但是,如果用户 dude
创建了第二个2008年iphone 4S对象,为此对象创建独特的插件的最佳方式是什么?我想要其他对象的URL看起来像:
http://www.mysite.com/phones/dude-2008- iphone-4S-2
和
http://www.mysite.com/phones/dude-2008-iphone-4S-3
http://www.mysite.com/phones/dude-2008- iphone-4S-4
#...等...
googling之后似乎有一些不同的方法来创建django的s o,这在尝试找出最佳实践时一直很混乱。
非常感谢有关这个问题的任何建议和澄清!
解决方案 p>最后我使用来覆盖我的模型中的电话保存方法。 py:
def save(self,** kwargs):
slug_str =%s%s%s% s%(self.user,self.year,self.model,self.series)
unique_slugify(self,slug_str)
super(Phone,self).save()
但是感谢jpic的贡献。
I have seen a variety of different methods for generating unique slugs: Ex. 1, Ex.2, Ex. 3, Ex. 4, etc. etc.
I want to create unique slugs upon saving a ModelForm. If my models are like:
class Phone(models.Model):
user = models.ForeignKey(User)
slug = models.SlugField(max_length=70, unique=True)
year = models.IntegerField()
model = models.ForeignKey('Model')
series = models.ForeignKey('Series')
Say that the Phone
object has the following values (via submitted ModelForm):
Phone.user = dude
Phone.year = 2008
Phone.model = iphone
Phone.series = 4S
I want the url for this object to appear like:
http://www.mysite.com/phones/dude-2008-iphone-4S
I understand that I should use slugify
via either signals or over-riding the save method to make this happen. But if user dude
creates a second 2008 iphone 4S object, what the best way to create a unique slug for this object? I want the additional objects's url to look like:
http://www.mysite.com/phones/dude-2008-iphone-4S-2
and
http://www.mysite.com/phones/dude-2008-iphone-4S-3
http://www.mysite.com/phones/dude-2008-iphone-4S-4
#...etc ...
After googling, it seems like there are a variety of different methods for creating slugs in django, which has been confusing when trying to figure out best practices.
Thanks a lot for any advice and clarification on this issue!
解决方案 I ended up using This Django Snippet to over-ride the save method of Phone in my models.py:
def save(self, **kwargs):
slug_str = "%s %s %s %s" % (self.user, self.year, self.model, self.series)
unique_slugify(self, slug_str)
super(Phone, self).save()
But thanks to jpic for the contribution.
这篇关于在Django中生成独特的插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!