Django:Slugify Post Data

时间:2012-08-08 04:36:26

标签: python django

我正在尝试保存用户输入的一些表单数据。我想强制用户输入的“名称”,但不希望slug字段显示在用户看到的模板上。我尝试使用您在下面看到的卖出功能手动完成,但无法让它工作。我想最终将slugified名称保存到我下面列出的Item模型中。我确信这比我目前使用的卖出功能更聪明/更简单:P。提前谢谢!

class Item(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=75)
    slug = models.SlugField(max_length=50, unique=True)
    is_active = models.BooleanField(default=True)
    image =  models.CharField(max_length=50)
    price = models.DecimalField(max_digits=9, decimal_places=2)
    quantity = models.IntegerField(default=1)
    description = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    shipping_price = models.DecimalField(decimal_places=2, max_digits=6)
    categories = models.ManyToManyField(Category)


class AddItem(forms.ModelForm):
    class Meta:
        model = Item
        exclude = ('user','slug','is_active',)

def sell(request):
        if request.method == "POST":
            form = AddItem(request.POST)
            item = form.save(commit=False)
            item.user = request.user
            item.is_active = True
            item.slug = slugify(form.name) **#not sure what this line should be?** 
            item.save()
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('thanks.html')
            else:
                url = urlresolvers.reverse('register')
                return HttpResponseRedirect(url)

2 个答案:

答案 0 :(得分:3)

您可以从用户表单中排除slug。 并且在pre_save信号中迷失了。

from django.dispatch import receiver
from django.db.models.signals import pre_save

@receiver(pre_save, sender=Item)
def iter_pre_save_handler(sender, instance, **kwargs):
    if not instance.pk:
        instance.slug = slugify(instance.name)

答案 1 :(得分:0)

根据docs,您可以排除某个字段在模型表单中呈现,如下所示:

class PartialAuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title')

class PartialAuthorForm(ModelForm):
    class Meta:
        model = Author
        exclude = ('birth_date',)

或在模型中的Field实例上设置editable = False。

完成此操作后,您可以覆盖模型的保存方法,因为OP中的注释已建议:

#  shamelessly copied from http://stackoverflow.com/questions/837828/how-do-i-create-a-slug-in-django/837835#837835
from django.template.defaultfilters import slugify

class test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()

    def save(self, *args, **kwargs):
        self.s = slugify(self.q)
        super(test, self).save(*args, **kwargs)