Django-如何从与其他值匹配的视图中渲染值? [英] Django - How can I render a value from views that matches a different value?

查看:71
本文介绍了Django-如何从与其他值匹配的视图中渲染值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:一个由用户添加的抽认卡组成,其中有一个问题和一个 answer 字段(来自我的 Flashcard 模型)。另一个由歌曲中的单词组成。然后,我创建了一个新列表,其中包含问题与歌词重叠的单词(代码中的 user_word

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).

现在在我的html中,我想创建一个表格,该表格在第一列中显示歌词中的单词,在第二列中显示单词的含义,(如果用户有 answer 字段。

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

...但是它只给我一个值,而不是每个字的正确值。我知道我的观点是错误的,并且我尝试了不同的方法,但到目前为止没有任何效果。我将不胜感激任何建议!我有点[strong]需要执行 vlookup的user_word列表中的歌词,然后返回 answer 。我该怎么做?

...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?

我的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...

推荐答案

我终于通过如下更改视图来解决了我的问题:

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']))

,然后在我的模板中:

 {% for item in combined %}
      <tr>
         <td>
           {{item.0}}
         </td>
         <td>
           {% if item.0 in user_flash %}
           {{item.1}}
           {% else %}
             xxx
            {% endif %}

这篇关于Django-如何从与其他值匹配的视图中渲染值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆