Reputation: 4745
I have a form used to create and edit an object on Django, and I'm trying to implement tags with django-taggit and Crispy Forms. Currently it's working great to create the tags, and it creates a list of tags for the field.
When I want to edit the object I get the field pre-populated with those tags, but they are not 'flattened', so the tags show as:
[<Tag:Tag1>
<Tag:Tag2>
<Tag:Tag3>]
rather than just
Tag1
Tag2
Tag3
And if the object contains no tags there is []
in the form field.
My view to edit the objects is:
def edit_recipe(request, recipe_id):
"""Edit an existing recipe"""
recipe = get_object_or_404(Recipe, pk=recipe_id)
if request.method == "POST":
form = RecipeForm(request.POST, request.FILES, instance=recipe)
if form.is_valid():
form.save()
messages.success(request, "Successfully updated recipe.")
return redirect(reverse("recipes"))
else:
messages.error(request, "Failed to update. Please check the form.")
else:
form = RecipeForm(instance=recipe)
template = "recipes/edit_recipe.html"
context = {"form": form, "recipe": recipe}
return render(request, template, context)
My model includes the field tags as so:
tags = TaggableManager(blank=True)
And my form is:
class RecipeForm(forms.ModelForm):
class Meta:
model = Recipe
fields = (
...
"tags",
)
widgets = {"tags": forms.TextInput(attrs={"data-role": "tagsinput"})}
I'm rendering the forms with Crispy Forms, like:
{% for field in form %}
{{ field | as_crispy_field }}
{% endfor %}
What do I need to do to populate the form to edit an already existing object with just the tags, and nothing at all when there are no tags in the object?
Thank you!
Upvotes: 3
Views: 333
Reputation: 35
forms.py
from taggit.forms import TagWidget
class ExampleForm(forms.ModelForm):
class Meta:
model = Example
fields = ('name', 'tags',)
widgets = {
'tags': TagWidget(
attrs={'class': 'form-control', 'id': 'tags', 'placeholder': 'Enter tags by comma separated',
'data-role': 'tagsinput'})
}
Upvotes: 0