jazzband / django-taggit

Simple tagging for django
https://django-taggit.readthedocs.io
BSD 3-Clause "New" or "Revised" License
3.27k stars 623 forks source link

DRF - Incorrectly processed Tag input string #884

Closed UnLuckyAki closed 6 months ago

UnLuckyAki commented 6 months ago

Tried to use the API to create new tags with request: tags: house, home, flat The problem is that TagListSerializerField(serializers.ListField) is converting this tags to ['house, home, flat'], so to_internal_value method proceed it like a single tag, which returns it as "tags": ["house, home, flat"]. Maybe I do sometthing wrong and will be gratefull for guidance. For now solved this with temporary fix (for comma only) in to_internal_value:

def to_internal_value(self, value):
    if isinstance(value, str):
        if not value:
            value = "[]"
        try:
            value = json.loads(value)
        except ValueError:
            self.fail("invalid_json")

    if not isinstance(value, list):
        self.fail("not_a_list", input_type=type(value).__name__)

    value = [item.strip() for item in value[0].split(',')] #  Temp Fix
    for s in value:
        if not isinstance(s, str):
            self.fail("not_a_str")

        self.child.run_validation(s)
rtpg commented 6 months ago

@UnLuckyAki why don't you send it as {tags: ["house", "home", "flat"]}? This is an API call right? You can send via a list.

UnLuckyAki commented 6 months ago

@rtpg, Thanks for the answer! It clarified me some questions. I was careless when reading the documentation, assuming that string values should be processed in the same way as in FormField. I also didn't use RAW requests, but the Web browsable API, which worked fine with one tag, but couldn't handle with several. And finally, I sent form-data in Postman, but did it incorrectly, wrong way: tags: ["house", "home", "flat"] right way:

tags: "house"
tags: "home"
tags: "flat"