I'm creating a Django website where users (who are learning Chinese) can upload Chinese vocabulary lists and the site will return a list of just the unique characters (no duplicates) that the user can download.
It's working and doing everything I described above. But the part that I'm stuck on is that I want to add a filter functionality. I want to add the option to exclude some of the more common Chinese characters from the list that the user downloads (what I'm thinking of as a filter feature).
I have created a dropdown menu where before the user presses upload, they first say whether they want to filter out the 100 most common characters, 500, none, etc. Then, they move to another page where it should take that into account when it's writing to the file that it presents for the user to download.
The logic of what I want to achieve would be something like: if the user selects one FilterPreference, then the web app should use the corresponding file in static files to filter out the characters in that file from the final output. I am fairly sure that I would need to use sessions, but I'm not positive about how to do it properly. Currently choosing a different FilterPreference does not affect the output. Open to any suggestions.
models.py
class FilterPreference(models.Model):
NONE = 'NO'
first_250 = 'F250'
first_500 = 'F500'
first_750 = 'F750'
first_1000 = 'F1000'
PREFERENCE_CHOICES = [
(NONE, 'None'),
(first_250, 'First 250'),
(first_500, 'First 500'),
(first_750, 'First 750'),
(first_1000, 'First 1000'),
]
preference = models.CharField(
max_length=100,
choices=PREFERENCE_CHOICES,
default=NONE,
)
def __str__(self):
return self.preference
forms.py
class FilterForm(forms.ModelForm):
class Meta:
model = FilterPreference
fields = ['preference']
labels = {'preference': ''}
views.py (likely problem area)
#Determine the filter
preference = request.session.get('preference')
if preference == 'None':
file_path = os.path.join(settings.STATIC_ROOT, 'converter/filter1.csv')
elif preference == 'First 250':
file_path = os.path.join(settings.STATIC_ROOT, 'converter/filter2.csv')
elif preference == 'First 500':
file_path = os.path.join(settings.STATIC_ROOT, 'converter/filter3.csv')
elif preference == 'First 750':
file_path = os.path.join(settings.STATIC_ROOT, 'converter/filter4.csv')
else:
file_path = os.path.join(settings.STATIC_ROOT, 'converter/filter5.csv')
views.py (full)
def index(request):
if request.method != 'POST':
#No data submitted; create a blank form.
form = FilterForm()
else:
#POST data submitted; process data.
form = FilterForm(data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('converter/file_upload')
preference = FilterForm.cleaned_data['preference']
request.session['preference'] = preference
context = {'form':form}
return render(request, "converter/index.html", context)
def file_upload(request):
success = 0
if success == 1:
success = 2
if request.POST and request.FILES:
txtfile = request.FILES['txt_file']
def char_isolate():
#Open and read the uploaded file
ur_text = txtfile.read().decode("utf-8")
text = []
for char in ur_text:
if char not in text:
text.append(char)
text = str(text)
#finding unique
unique = []
for char in text:
if char not in unique:
unique.append(char)
unique = str(unique)
#cleaning
import string
nopunct_unique = unique.translate(str.maketrans('', '', string.punctuation))
nodigit_unique = nopunct_unique.translate(str.maketrans('', '', string.digits))
noletter_unique = nodigit_unique.translate(str.maketrans('', '', string.ascii_letters))
nochinesepunct_unique = noletter_unique.translate({ord(c): None for c in '。;:!?,、'})
clean_unique = nochinesepunct_unique.translate({ord(c): None for c in string.whitespace})
#Determine the filter
preference = request.session.get('preference')
if preference == 'None':
file_path = os.path.join(settings.STATIC_ROOT, 'converter/filter1.csv')
elif preference == 'First 250':
file_path = os.path.join(settings.STATIC_ROOT, 'converter/filter2.csv')
elif preference == 'First 500':
file_path = os.path.join(settings.STATIC_ROOT, 'converter/filter3.csv')
elif preference == 'First 750':
file_path = os.path.join(settings.STATIC_ROOT, 'converter/filter4.csv')
else:
file_path = os.path.join(settings.STATIC_ROOT, 'converter/filter5.csv')
#Filter out common characters
filter_file = str(file_path)
filter=set([])
for word in filter_file:
filter.add(word)
filtered = set([])
for word in clean_unique:
if word not in filter:
filtered.add(word)
#write to file
f = open("text.txt","w+")
for word in filtered:
f.write('\n'+word)
f.close()
#write to file
tmp_path = os.path.join(settings.MEDIA_ROOT, 'tmp/text.txt')
with open(tmp_path, 'w') as f:
item = iter(filtered)
for _ in range(len(filtered)-1):
f.write('%s\n' % next(item))
f.seek(0)
f.write('%s' % next(item))
f.close()
char_isolate()
success = 1
return redirect('converter:file_download')
context = {}
return render(request, "converter/file_upload.html", locals())
def download(request):
path = "tmp/text.txt"
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as f:
try:
response = HttpResponse(f)
response['content_type'] = "application/octet-stream"
response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path)
return response
except Exception:
raise Http404