简体   繁体   中英

Django how to concatenate form data before saving to the database

I am building a budgeting web app for many users. 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.

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. How can I modify the users AccountName in the form to be AccountName + userid?

Desired AccountName examples in the database: Cash1, Cash2

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

    @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']

Get AccountName from form input by getting it from cleaned_data then concat with request.user.pk . Don't forget to convert pk value into str otherwise you will getting TypeError exception

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

Also your AccountName variable does not represent anything thanks to Eby Sofyan's answer

To fix your problem replace,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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