如何在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:
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>
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/", } ) }
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})
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.
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

