Dict in Django TemplateView throws Server Error 500, Suggested to use ListView that helps for DetailView

huangapple go评论61阅读模式
英文:

Dict in Django TemplateView throws Server Error 500, Suggested to use ListView that helps for DetailView

问题

I'm here to provide translations for the code you've provided. Here are the translated parts:

我正试图利用字典 **prices** 从雅虎金融中获取股票价格。而 Django 数据库是我获取股票代码的地方。在 HTML 中,我无法使用 dict。请查看我下面包含的代码示例。

如果变量 "prices" 的数据类型也是一个字典,Django 会产生一个 500 服务器错误。我需要从雅虎金融获取股票价格,并在 HTML 中显示来自 Django 数据库的股票代码。我该如何解决这个问题?

请给我一些关于如何使用 ListView 显示我的币种的建议。为了帮助我使用 DetailView,这对我的在线应用程序至关重要。

我想说谢谢。

**模型:**
```python
class Coin(models.Model):
    ticker = models.CharField(max_length=10)

    def __str__(self):
        return self.ticker

视图:

class BucketView(LoginRequiredMixin, TemplateView):
    template_name = 'coinbucket/bucket.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        symbols = [symbol.ticker for symbol in Coin.objects.all()]

        prices = {}
        for symbol in symbols:
            ticker = yf.Ticker(symbol)
            price = ticker.history(period='1d')['Close'][0]
            prices[symbol] = f'$ {price:.6f}'

        context["prices"] = prices
        return context

模板:

{% for coin in coins %}
    <div class="col-12 col-md-8 my-2">
        <div class="card">
            <div class="card-body">
                <div class="row">
                    <div class="col">{{ coin }}</div>
                    <div class="col">{{ prices[coin] }}</div>
                </div>
            </div>
        </div>
    </div>
{% endfor %}

字典 prices 的值:

{'BTC-USD': '$ 29335.927734', 'ETH-USD': '$ 1987.428223', 'XRP-USD': '$ 0.498745', 'DOGE-USD': '$ 0.090749', 'LTC-USD': '$ 94.516197'}

尝试了以下代码片段,但没有结果:

<div class="col">{{ prices['coin'] }}</div>
<div class="col">{{ prices.coin }}</div>
<div class="col">{{ prices.get(coin, 'N/A') }}</div>

希望这有助于您理解和解决问题。
英文:

I'm attempting to utilise the dictionary prices to retrieve the stock prices from yahoo finance. And the Django database is where I get my stock tickers. In HTML, I am unable to utilise dict. Please review the code samples I've included below.

If the datatype for the variable "prices" is likewise a dict, Django produces a 500 server error. I need to pull stock prices from yahoo finance and show stock tickers from the Django database in HTML. How can I fix it?

Please give me some advice on how to show my coins using ListView. In order to assist me with DetailView, which is crucial to my online application.

I want to say thank you.

Model:

class Coin(models.Model):
    ticker = models.CharField(max_length=10)

    def __str__(self):
        return self.ticker

View:

class BucketView(LoginRequiredMixin, TemplateView):
    template_name = &#39;coinbucket/bucket.html&#39;

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        symbols = [symbol.ticker for symbol in Coin.objects.all()]

        prices = {}
        for symbol in symbols:
            ticker = yf.Ticker(symbol)
            price = ticker.history(period=&#39;1d&#39;)[&#39;Close&#39;][0]
            prices[symbol] = f&#39;$ {price:.6f}&#39;

        context[&quot;prices&quot;] = prices
        return context

Template:

{% for coin in coins %}
    &lt;div class=&quot;col-12 col-md-8 my-2&quot;&gt;
        &lt;div class=&quot;card&quot;&gt;
            &lt;div class=&quot;card-body&quot;&gt;
                &lt;div class=&quot;row&quot;&gt;
                    &lt;div class=&quot;col&quot;&gt;{{ coin }}&lt;/div&gt;
                    &lt;div class=&quot;col&quot;&gt;{{ prices[coin] }}&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
{% endfor %}

Values of dict prices:

{&#39;BTC-USD&#39;: &#39;$ 29335.927734&#39;, &#39;ETH-USD&#39;: &#39;$ 1987.428223&#39;, &#39;XRP-USD&#39;: &#39;$ 0.498745&#39;, &#39;DOGE-USD&#39;: &#39;$ 0.090749&#39;, &#39;LTC-USD&#39;: &#39;$ 94.516197&#39;}

Following code snippets are tried, but no results:

&lt;div class=&quot;col&quot;&gt;{{ prices[&#39;coin&#39;] }}&lt;/div&gt;
&lt;div class=&quot;col&quot;&gt;{{ prices.coin }}&lt;/div&gt;
&lt;div class=&quot;col&quot;&gt;{{ prices.get(coin, &#39;N/A&#39;) }}&lt;/div&gt;

答案1

得分: 1

你不能像这样在Django模板语言中访问字典:

<div class="col">{{ prices[coin] }}</div>

尝试这样

<div class="col">{{ prices.coin }}</div>
英文:

you cannot access a dictionary like this in django-template-language

&lt;div class=&quot;col&quot;&gt;{{ prices[coin] }}&lt;/div&gt;

try this

&lt;div class=&quot;col&quot;&gt;{{ prices.coin }}&lt;/div&gt;

huangapple
  • 本文由 发表于 2023年4月20日 00:20:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定