有没有用 django 从模板中的表单字段预填充一个 slug 字段?

is there anyway to pre-populate a slug field from the form fields in the template with django?

美好的一天。 我的 admin.py 中有以下 slug 字段:

prepopulated_fields = {'slug': ('title',)}

在我的 forms.py:

class BookForm(forms.ModelForm):
class Meta:
        model = Book

        fields = [

            'username',
            'book',
            'slug',
            'password1',
            'password2',
        ]

在我的模板中:

    <from method=post action=''>
{% csrf_token %}
{{ form.py }}
</form>

谢谢

正如@yedpodtrzitko 在评论中所建议的那样,prepoluated_fields 仅适用于管理界面。如果你想在你的视图中使用相同的 slugfied 字段,你必须在任何你想要的地方(例如在你的 views.py 中)通过使用 Django 内部使用的相同 slugify 方法自己对字段进行 slugify :

from django.utils.text import slugify

#wherever you want a slug:
mystring = 'a string to slugified'
slugified_string = slugify(mystring) #will output a-string-to-slugified