表单仅在单击提交按钮后显示

我已经检查了有关根本没有显示的表单的类似帖子,并且我已经尝试应用修复程序,但它并没有为我修复它。我有以下几点:


股票.html:


<form method="post" class="form-inline my-2 my-lg-0">

  {% csrf_token %}

  {{ symbol_form }}

  <button class="btn btn-secondary my-2 my-sm-0" type="submit">Add Stock</button>

</form>

视图.py:


class PortfolioStockListView(ListView):

    model = StockPortfolio

    template_name = 'stocks.html'


    def post(self, request):

        symbol_form = StockSymbolForm(request.POST)


        if request.method == 'POST':

            if symbol_form.is_valid():

                model_instance = symbol_form.save(commit=False)

                model_instance.timestamp = timezone.now()

                model_instance.save()

                return redirect('/')    

            else:

                return render(request, 'stocks.html', {'symbol_form': symbol_form})


        else:

            symbol_form = StockSymbolForm()

            return render(request, 'stocks.html', {'symbol_form': symbol_form})

形式.py:


class StockSymbolForm(ModelForm):

    class Meta:

        model = StockPortfolio

        fields = ['username', 'stock_symbol' , 'stock_qty']

模型.py:


class StockPortfolioUser(models.Model):

    username = models.OneToOneField(User, on_delete=models.CASCADE)

    usercash = models.PositiveIntegerField(default=100000)


class StockPortfolio(models.Model):

    username = models.ForeignKey(StockPortfolioUser, on_delete=models.CASCADE)

    stock_symbol = models.CharField(max_length=5)

    stock_qty = models.PositiveIntegerField(default=0)

如何解决导致表单隐藏直到单击按钮的问题?如有必要,我可以从其他文件共享更多代码。


小怪兽爱吃肉
浏览 148回答 1
1回答

慕的地6264312

将其传递给您的模板覆盖get_context_data方法class PortfolioStockListView(ListView):&nbsp; &nbsp; model = StockPortfolio&nbsp; &nbsp; template_name = 'stocks.html'&nbsp; &nbsp; def get_context_data(self, *, object_list=None, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; context = super(PortfolioStockListView, self).get_context_data(object_list=object_list, **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; context['symbol_form'] = StockSymbolForm()&nbsp; &nbsp; &nbsp; &nbsp; return context&nbsp; &nbsp; def post(self, request):&nbsp; &nbsp; &nbsp; &nbsp; ...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python