【发布时间】:2017-03-24 07:49:30
【问题描述】:
我的模型有 Meta: unique_together = ['slug', 'person'], person 是外键字段。在我的表单中,我不想输入 slug 字段。我想从 child_name 字段填充它。我试过了:
class ChildForm(SlugCleanMixin, forms.ModelForm):
class Meta:
model = Child
fields = ('child_name','slug','child_birth_date','blood_group')
def slug(self):
return slugify(self.child_name)
但 slug 字段未从 child_name 自动填充。我还尝试在模型中使用 pre_save:
def create_slug(instance, new_slug=None):
slug = slugify(instance.child_name)
if new_slug is not None:
slug = new_slug
qs = Child.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=Child)
但没有什么能达到我的目的。我怎么能那样做?任何帮助将不胜感激。
我的 SlugCleanMixin:
class SlugCleanMixin:
"""Mixin class for slug cleaning method."""
def clean_slug(self):
new_slug = (
self.cleaned_data['slug'].lower())
if new_slug == 'create':
raise ValidationError(
'Slug may not be "create".')
return new_slug
我的观点:
class ChildrenCreate( ChildrenGetObjectMixin,
PersonContextMixin, CreateView):
template_name = 'member/children_form.html'
model = Child
form_class = ChildForm
def get_initial(self):
person_slug = self.kwargs.get(
self.person_slug_url_kwarg)
self.person = get_object_or_404(
Person, slug__iexact=person_slug)
initial = {
self.person_context_object_name:
self.person,
}
initial.update(self.initial)
return initial
型号:
class Child(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
child_name = models.CharField(max_length=150)
slug = models.SlugField(max_length=100)
child_birth_date = models.DateField()
blood_group = models.CharField(max_length=5, blank=True)
objects = ChildrenManager()
class Meta:
verbose_name_plural = 'children'
ordering = ['-child_birth_date']
unique_together = ['slug', 'person']
【问题讨论】:
-
你能把你
SlugCleanMixin课程的内容贴出来吗? -
请添加您的模型和视图
-
你试过通过调试器运行它吗?例如,您根本没有在 create_slug 方法中处理 slug = None 条件
-
我添加了我的 SlugCleanMixin 并查看了有问题的模型。我没有在调试器中尝试过。
-
github.com/mozilla/unicode-slugify/issues/… 中描述的方法可能对您有用。