以django形式包含名称字段

时间:2016-11-10 10:13:44

标签: django forms slugify

我的模型有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)

但没有达到我的目的。我怎么能这样做?任何帮助将不胜感激。

MY 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']

2 个答案:

答案 0 :(得分:0)

我会尝试检查这个软件包以生成slug,因为我已在多个应用程序中使用过,并认为它很棒:

https://github.com/un33k/django-uuslug

它们提供了一个简单的使用示例,适用于您的模型:

class Child(models.Model):
    child_name = models.CharField(max_length=150)
    slug = models.SlugField(max_length=100)
    ...

    def save(self, *args, **kwargs):
        self.slug = uuslug(self.child_name, instance=self)
        super(Child, self).save(*args, **kwargs)  

答案 1 :(得分:0)

首先从表单字段中删除slug,因为您不需要从用户那里获取。表格将不参与其中。所以你的表格如下:

class ChildForm(SlugCleanMixin, forms.ModelForm):
    class Meta:
        model = Child
        fields = ('child_name','child_birth_date','blood_group')

然后,在您的模型中覆盖保存功能。所以,它变成了这样的东西:

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()

    def save(self):
        if self._created or 'child_name' in self._get_changed_fields():
            self.slug = create_slug(self)


    class Meta:
        verbose_name_plural = 'children'
        ordering = ['-child_birth_date']
        unique_together = ['slug', 'person']

你完成了。希望这能解决你的问题。