3
>>> x = "first, second, third,"
>>> y = [ele for ele in x.split(',') if ele]
>>> y
['first', ' second', ' third']
Using the fact that non empty strings return True
.
- [Django]-Django β Escaping quotes in a template
- [Django]-Django-Tagging β count and ordering top "tags" (Is there a cleaner solution to mine?)
- [Django]-See if node exists before creating in NeoModel
- [Django]-Can I include partial view in Web2Py, passing specific variables into it?
1
Do you really want to use lstrip() rather than strip() for processing the tags? What if the user enters abc , def
; do you really want to allow a tag "abc "
with a trailing space?
If you really want to strip the tags on both sides (which I think you do), then itβs a simple matter of doing that and then omitting the empty ones:
try: # EAFP
tags = (tag.strip() for tag in request.POST['tags'].split(','))
tag_list = [Tag.objects.get_or_create(name = tag)[0] for tag in tags if tag]
# 'if tag' is the operative "filtering" bit
except KeyError: pass
- [Django]-Postgres to Ubuntu Docker container linking not working
- [Django]-Inherit and modify a `Meta` class
- [Django]-Error when installing mysqlclient
- [Django]-Using reverse relationships with django-rest-framework's serializer
0
tag_list = [tag.lstrip() for tag in tags.split(",") if len(tag.lstrip())>0]
will generate the tag_list without the empty character.
Rest should be simple.
- [Django]-Execute background process from django that can't be interrupted by the web server
- [Django]-Django after login return to last page
- [Django]-Python manage.py runserver: TypeError: argument 1 must be str not WindowsPath
0
You could do all your tags
processing in once place, so you donβt have to
call tag.lstrip()
inside get_or_create(name = ...)
:
if "tags" in request.POST:
tags = request.POST["tags"]
tags = (tag.lstrip() for tag in tags.split(',') if tag.strip())
tag_list = [Tag.objects.get_or_create(name = tag)[0] for tag in tags]
- [Django]-How to use django-ckeditor to upload files and browser files on server in admin?
- [Django]-How do I append a list to FormData?
- [Django]-OperationalError: (2019, ""Can't initialize character set utf8mb4 (path: C:\\mysql\\\\share\\charsets\\)"")
- [Django]-Invalid block tag: 'endblock' django
0
If your tags are actually set individually in the same variable instead of as a string list you have the option of just writing:
filter(len, map(str.strip, request.POST.getlist("keys")))
Without having to parse a string list manually.
- [Django]-What file or module actually generates "It worked" in Django tutorials?
- [Django]-Django class view with decorator and sessions
- [Django]-BASE_DIR returning settings path and not project path (django 1.10)