简体   繁体   English

Django 如何在保存到数据库之前连接表单数据

[英]Django how to concatenate form data before saving to the database

I am building a budgeting web app for many users.我正在为许多用户构建预算 web 应用程序。 The user creates accounts to track different values.用户创建帐户以跟踪不同的值。 The problem is that I cannot make a composite key and need the AccountName to be the primary key.问题是我不能制作复合键,需要 AccountName 作为主键。

This poses a challenge.这带来了挑战。 What if users make the same account name?如果用户使用相同的帐户名怎么办? This will happen as some users may make a "Cash" account.这会发生,因为一些用户可能会创建一个“现金”帐户。 My solution to this problem is to name the account in the database the AccountName + the userid.我对这个问题的解决方案是将数据库中的帐户命名为 AccountName + userid。 How can I modify the users AccountName in the form to be AccountName + userid?如何将表单中的用户 AccountName 修改为 AccountName + userid?

Desired AccountName examples in the database: Cash1, Cash2数据库中所需的 AccountName 示例:Cash1、Cash2

models.py模型.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)

Views.py视图.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 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']

Get AccountName from form input by getting it from cleaned_data then concat with request.user.pk .通过从cleaned_data获取AccountName从表单输入获取,然后与request.user.pk连接。 Don't forget to convert pk value into str otherwise you will getting TypeError exception不要忘记将pk值转换为str否则你会得到TypeError异常

....
account.AccountName = form.cleaned_data.get('AccountName') + str(request.user.pk)
account.save()

request.user will not work because it is an object which contains other fields. request.user将不起作用,因为它是包含其他字段的 object。

Also your AccountName variable does not represent anything thanks to Eby Sofyan's answer由于 Eby Sofyan 的回答,您的AccountName变量也不代表任何内容

To fix your problem replace,要解决您的问题更换,

account.AccountName = form.cleaned_data.get('AccountName') + str(request.user.id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM