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

时间:2018-12-25 04:16:24

标签: python django django-forms

我检查了有关表单完全不显示的类似帖子,并且我尝试应用了这些修复程序,但是它并没有为我修复。我有以下内容:

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

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

forms.py

class StockSymbolForm(ModelForm):
    class Meta:
        model = StockPortfolio
        fields = ['username', 'stock_symbol' , 'stock_qty']

models.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 个答案:

答案 0 :(得分:2)

将其传递给您的模板覆盖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):
        ...