为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

小怪兽爱吃肉 2021-09-24 16:51:42
我已经检查了有关根本没有显示的表单的类似帖子,并且我已经尝试应用修复程序,但它并没有为我修复它。我有以下几点:股票.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)如何解决导致表单隐藏直到单击按钮的问题?如有必要,我可以从其他文件共享更多代码。
查看完整描述

1 回答

?
慕的地6264312

TA贡献1817条经验 获得超6个赞

将其传递给您的模板覆盖get_context_data方法


class PortfolioStockListView(ListView):

    model = StockPortfolio

    template_name = 'stocks.html'


    def get_context_data(self, *, object_list=None, **kwargs):

        context = super(PortfolioStockListView, self).get_context_data(object_list=object_list, **kwargs)

        context['symbol_form'] = StockSymbolForm()

        return context


    def post(self, request):

        ...


查看完整回答
反对 回复 2021-09-24
  • 1 回答
  • 0 关注
  • 147 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信