I'm working on a translator program. I want the result to appear at the bottom of the original page when the user presses the 'Submit' button.
I created a function in 'views.py' and returned the result in the form of a DataFrame (I checked that this Python code itself is fine) and I got an error called 'context must be a dictator than data frame'. I tried several ways to change it to dict format, but it only caused other errors.
This is my 'views.py' code and 'urls.py' code. Please let me know if there is anything wrong.
views.py
class Postview(View):
@csrf_exempt
def success(request):
content = request.POST.get('content')
dict = pd.read_csv("C:\\Users\\user\\jeju-dialect-translation\\jeju\\dialect\\dict2.csv", sep=",", encoding='cp949')
hannanum = Hannanum()
okt = Okt()
nouns = hannanum.nouns(content)
stem = okt.morphs(content, stem = True)
tempt=[]
for i in range(0, len(stem)):
if (len(stem[i]) == 1):
tempt.append(stem[i])
adjective = list(set(stem) - set(tempt))
results = pd.DataFrame(columns = {'siteName', 'contents'})
for i in nouns:
x = dict[dict['siteName'] == i]
x = x[['siteName', 'contents']]
results = pd.concat([results, x], axis = 0)
for i in adjective:
y = dict[dict['siteName'].str.match(i)]
results = pd.concat([results, y], axis = 0)
context = results.drop_duplicates()
return render(request, 'dialect/trans_suc.html', context)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('dialect/', views.Postview.as_view(), name='main_page'),
path('trans/', views.Postview.success, name='trans_suc')
]
CodePudding user response:
You can use Pandas to_dict method, https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html
context = results.to_dict()
‘dict’ (default) : dict like {column -> {index -> value}}
‘list’ : dict like {column -> [values]}
‘series’ : dict like {column -> Series(values)}
‘split’ : dict like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}
‘tight’ : dict like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values], ‘index_names’ -> [index.names], ‘column_names’ -> [column.names]}
‘records’ : list like [{column -> value}, … , {column -> value}]
‘index’ : dict like {index -> {column -> value}}
CodePudding user response:
A Django context is a dictonary type object. To learn more about it, follow this link. Basically, what you can do to resolve this error is to:
dropped_duplicates_result = results.drop_duplicates()
context = dropped_duplicates_result.to_dict()
Here, you're dropping the duplicates, then converting it to a "dictionary" type object because contexts are dictionary type.
Docs for pandas.DataFrame.to_dict()