无法在数据库中找到新保存的实例

时间:2018-12-26 22:47:28

标签: python django django-models

我正在将股票投资组合应用程序作为个人项目。我有一个StockSymbolForm表格,用于购买股票。它具有以下字段:usernamestock_symbolstock_qty

我将username设置为当前正在使用该应用程序的当前用户-因此,他们只需要填写stock_symbolstock_qty

提交有效表单后,我进入管理页面进行检查,但是我没有看到新的stock_symbolstock_qty添加到模型中。

这是我的代码:

views.py

类PortfolioStockListView(ListView):     模型= StockPortfolio     template_name ='stocks.html'

def post(self, request):
    current_user = StockPortfolioUser.objects.filter(username=request.user).first()

if request.method == 'POST':
    symbol_form = StockSymbolForm(request.POST, initial={'username': current_user})

    if symbol_form.is_valid():
        symbol_form = StockSymbolForm(request.POST, instance=current_user)
        model_instance = symbol_form.save(commit=True)
        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})

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)

forms.py

StockSymbolForm(ModelForm)类:

class Meta:
    model = StockPortfolio
    fields = ('stock_symbol' , 'stock_qty')
    labels = {'stock_symbol': 'Stock Symbol', 'stock_qty': 'Quantity'}

如何正确保存模型实例?为什么现在不保存呢?

2 个答案:

答案 0 :(得分:1)

好吧,您似乎从未设置过用户名。您设置了一个时间戳记,该时间戳记不作为字段存在,但不是实际的用户名字段。

    model_instance = symbol_form.save(commit=True)
    model_instance.userame = request.user
    model_instance.save()

顺便说一句,该字段应称为user,因为它指向整个User对象而不仅仅是用户名。

答案 1 :(得分:1)

在您的views.py文件中对此进行更改

model_instance = symbol_form.save(commit=False)
model_instance.username = request.user.id
model_instance.timestamp = timezone.now()
model_instance.save()

StockSymbolForm中更改

fields = ('username', 'stock_symbol' , 'stock_qty')