![](/img/trans.png)
[英]Django: How to check if data is correct before saving it to a database on a post request?
[英]Django how to concatenate form data before saving to the database
我正在為許多用戶構建預算 web 應用程序。 用戶創建帳戶以跟蹤不同的值。 問題是我不能制作復合鍵,需要 AccountName 作為主鍵。
這帶來了挑戰。 如果用戶使用相同的帳戶名怎么辦? 這會發生,因為一些用戶可能會創建一個“現金”帳戶。 我對這個問題的解決方案是將數據庫中的帳戶命名為 AccountName + userid。 如何將表單中的用戶 AccountName 修改為 AccountName + userid?
數據庫中所需的 AccountName 示例:Cash1、Cash2
模型.py
class Account(models.Model):
DateCreated = models.DateTimeField()
AccountName = models.CharField(max_length= 100, primary_key=True)
UserID = models.ForeignKey(MyUser, on_delete=models.CASCADE)
Type = models.CharField(max_length= 20)
Balance = models.DecimalField(max_digits=19, decimal_places=8)
Value = models.DecimalField(max_digits=19, decimal_places=8)
視圖.py
@login_required
def func_AccountsView(request):
# This filters users accounts so they can only see their own accounts
user_accounts = Account.objects.filter(UserID_id=request.user).all()
if request.method == 'POST':
form = AddAccount(request.POST)
if form.is_valid():
account = form.save(commit=False)
account.UserID = request.user
account.AccountName = AccountName + str(request.user) # WHY DOES THIS NOT WORK?
account.save()
return redirect('accounts')
else:
form = AddAccount()
else:
form = AddAccount()
data = {
'form':form,
'data': user_accounts
}
return render(request, 'NetWorth/accounts.html', data)
forms.py
class AddAccount(forms.ModelForm):
''' This is the form that handles additions of an account '''
class Meta:
model = Account
fields = ['AccountName','DateCreated', 'Type', 'Balance', 'Value']
通過從cleaned_data
獲取AccountName
從表單輸入獲取,然后與request.user.pk
連接。 不要忘記將pk
值轉換為str
否則你會得到TypeError
異常
....
account.AccountName = form.cleaned_data.get('AccountName') + str(request.user.pk)
account.save()
request.user
將不起作用,因為它是包含其他字段的 object。
由於 Eby Sofyan 的回答,您的AccountName
變量也不代表任何內容
要解決您的問題更換,
account.AccountName = form.cleaned_data.get('AccountName') + str(request.user.id)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.