You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django后台管理面板外使用django-tagit-labels?

Got it, let's get django-tagit-labels working on your custom Django pages! Here's a step-by-step breakdown that mirrors the admin experience but works on your own frontend forms:

1. Load Required Static Assets First

Since django-tagit-labels was built for the admin, you'll need to manually include its CSS and JS files in your custom template. Don't forget it depends on jQuery too.

Add this to your template's <head> section:

{% load static %}

<!-- Tagit styles -->
<link rel="stylesheet" type="text/css" href="{% static 'tagit_labels/css/jquery.tagit.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'tagit_labels/css/tagit_labels.css' %}">

<!-- jQuery (use your project's existing jQuery if you have one) -->
<script src="{% static 'admin/js/jquery.js' %}"></script>
<script src="{% static 'tagit_labels/js/tag-it.js' %}"></script>
<script src="{% static 'tagit_labels/js/tagit_labels.js' %}"></script>
2. Build a Custom Form with the Tagit Widget

In your forms.py, create a form class that uses the TagitLabelsWidget instead of the default admin-only widget. This works with any model that uses django-taggit's TaggableManager.

Example:

from django import forms
from tagit_labels.widgets import TagitLabelsWidget
from .models import YourModel

class CustomTagForm(forms.ModelForm):
    class Meta:
        model = YourModel
        fields = ["tags", "title", "content"]  # Add your other fields
        widgets = {
            "tags": TagitLabelsWidget(
                attrs={
                    "placeholder": "Type and press Enter to add tags...",
                    # Optional: Add autocomplete support later
                    "data-autocomplete-url": "/tag-autocomplete/",
                }
            )
        }
3. Handle the Form in Your View

Treat this form like any other Django form in your view function or class-based view:

from django.shortcuts import render, redirect
from .forms import CustomTagForm

def custom_tag_page(request):
    if request.method == "POST":
        form = CustomTagForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect("success-page")  # Redirect after save
    else:
        form = CustomTagForm()
    
    return render(request, "custom_tag_page.html", {"form": form})
4. Render and Initialize the Widget in Your Template

Render the form in your template, then add a script to initialize the tagit component:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }} <!-- Or render fields manually for more control -->
    <button type="submit">Save</button>
</form>

<script>
$(document).ready(function() {
    // Initialize the tagit widget on your tags field
    $("#id_tags").tagitLabels({
        allowNewTags: true,  // Let users create new tags (toggle as needed)
        // Enable autocomplete if you set up the URL earlier
        autocomplete: {
            source: $("#id_tags").data("autocomplete-url"),
            delay: 200
        }
    });
});
</script>

Note: #id_tags is Django's default ID for the field—adjust it if you set a custom ID in your form widget.

Optional: Add Tag Autocomplete

If you want autocomplete for existing tags, create a simple view to return tag data as JSON:

from django.http import JsonResponse
from taggit.models import Tag

def tag_autocomplete(request):
    search_term = request.GET.get("term", "")
    matching_tags = Tag.objects.filter(name__icontains=search_term).values_list("name", flat=True)
    return JsonResponse(list(matching_tags), safe=False)

Then add a URL route for it in urls.py:

from django.urls import path
from .views import tag_autocomplete

urlpatterns = [
    # ... your other URLs
    path("tag-autocomplete/", tag_autocomplete, name="tag-autocomplete"),
]

Update your form widget's data-autocomplete-url to use {% url 'tag-autocomplete' %} for dynamic routing.

That's it! You'll have the same tag management experience from the admin panel on your custom page.

内容的提问来源于stack exchange,提问作者Marco Rizk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:00:32