问题
I have two lists: one consists of user added flashcards, which have a question
and an answer
field (from my Flashcard
model). The other consists of words in a song. Then I've made a new list that contains the words where the question
overlaps with the lyrics (user_word
in my code below).
Now in my html I want to make a table that shows in one column the word from the lyrics, and in the second column the word's meaning, which (if the user has already added the word as a flashcard) will be the answer
field.
So far my views are as follows:
class SongVocab(LoginRequiredMixin, generic.DetailView):
model= models.Song
template_name = 'videos/song_vocab.html'
context_object_name = 'song'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
from pymystem3 import Mystem
m = Mystem()
user_flash = Flashcard.objects.filter(owner=self.request.user).values_list('question', flat=True)
lyrics_list = models.Song.objects.get().lyrics_as_list()
user_flash_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(user_flash))]
user_flash_clean = [w for w in user_flash_ if w.strip()] ##removes empty strings
lyrics_list_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(lyrics_list))]
lyrics_list_clean = [w for w in lyrics_list_ if len(w.strip())]
user_word = list(set(user_flash_clean) & set(lyrics_list_clean))
import icu # PyICU
def sorted_strings(strings, locale=None):
if locale is None:
return sorted(strings)
collator = icu.Collator.createInstance(icu.Locale(locale))
return sorted(strings, key=collator.getSortKey)
context['percent_known'] = ((len(user_word))/(len(set(lyrics_list_clean))))*100
context['lyrics'] = sorted_strings(set(lyrics_list_clean),"ru_RU.UTF8")
context['user_flash'] = user_flash_clean
context['flash_answer'] = []
for word in user_word:
flash = Flashcard.objects.get(owner=self.request.user, question=word)
context['flash_answer'].append(flash.answer)
return context
I don't know how to connect the word lyric with the user flashcard answer field. I've tried this...
user_word = user_word
lyrics = lyrics_list_clean
context['test'] = {}
for word in user_word:
flash = Flashcard.objects.get(owner=self.request.user, question=word)
answer = flash.answer
question = flash.question
if question in lyrics:
dict = {'lyric_word': question,'answer': answer}
context['test'] = dict
...but it gives me just one value, not the right value for every word. I know my views are wrong, and I've tried different things, but nothing has worked so far. I would greatly appreciate any advice! I kind of need to do a "vlookup" of the lyric word in the user_word list and then return answer
. How can I do this?
My html:
{% for item in lyrics %}
<tr class='lyrics-table'>
<td>{{item}}</td>
<td>
{% if item in user_flash %}
<p>{{test.answer}}</p>
{% else %}
xxxx
{% endif %}
</td>
</tr>
{% endfor %}
I also tried the following, which seems to be a step in the right direction, but I am struggling to render it in my template:
z = []
dict_lyrics = {'question': [], 'answer': []}
for word in user_word:
x = lyrics_list_clean.index(word)
y = user_word.index(word)
flash = Flashcard.objects.get(owner=self.request.user, question=word)
z.append(flash.answer)
dict_lyrics['question'].append(lyrics_list_clean[x])
dict_lyrics['answer'].append(z[y])
context['question'] = dict_lyrics['question']
context['answer'] = dict_lyrics['answer']
context['dict_lyrics'] = dict_lyrics
Update - I added the following in my views:
context['combined'] = list(zip(dict_lyrics['question'], dict_lyrics['answer']))
Which I can access for example like this in my template:
{% for i, j in combined %}
{{ i }} -- {{ j }}
{% endfor %}
Which helps, but doesn't solve my problem...
回答1:
I finally solved my problem by changing my views as follows:
from django.core.exceptions import ObjectDoesNotExist
z = []
dict_lyrics = {'question': [], 'answer': z}
for word in sorted_strings(set(lyrics_list_clean),"ru_RU.UTF8"):
try:
flash = Flashcard.objects.get(owner=self.request.user, question=word)
z.append(flash.answer)
except ObjectDoesNotExist:
flash = ""
z.append(flash)
dict_lyrics['question'] = sorted_strings(set(lyrics_list_clean),"ru_RU.UTF8")
context['question'] = dict_lyrics['question']
context['answer'] = dict_lyrics['answer']
context['dict_lyrics'] = dict_lyrics
context['length'] = len(dict_lyrics['question'])
context['combined'] = list(zip(dict_lyrics['question'], dict_lyrics['answer']))
And then in my template:
{% for item in combined %}
<tr>
<td>
{{item.0}}
</td>
<td>
{% if item.0 in user_flash %}
{{item.1}}
{% else %}
xxx
{% endif %}
来源:https://stackoverflow.com/questions/62620352/django-how-can-i-render-a-value-from-views-that-matches-a-different-value