【问题标题】:Cannot assign "''": "IncomeExpense.username" must be a "User" instance无法分配“''”:“IncomeExpense.username”必须是“用户”实例
【发布时间】:2020-12-05 14:26:24
【问题描述】:

我正在处理下面的代码,尝试通过从表单中获取值来将数据添加到表中。我还用# 标记了我收到错误的位置。

我在下面粘贴了views.pymodels.pycreateentry.html。我收到此错误的原因可能是什么,并解释了我可以更改哪些内容来消除此错误。

#views.py

def create_entry_form(request):
    if request.method=='POST':
        entry_type=request.POST.get("expensetype")
        amount=request.POST.get("amount")
        details=request.POST.get("entrydetails")
        capture_date=time.strftime('%Y-%m-%d')
        entry_username=request.POST.get("entryusername")

        entry=IncomeExpense.objects.create(entry_type=entry_type, amount=amount, details=details, capture_date=capture_date, username=entry_username) #getting_error_in_this_line
        entry.save()
        user_balance = UserBalance.objects.filter(username=username).values_list('balance', flat=True)[0]
        if entry_type=="income":
            total_balance = user_balance + amount
        else:
            total_balance=user_balance - amount


        update_balance=UserBalance.objects.get(username=username)
        update_balance.value=total_balance
        update_balance.save()
        return render(request, "homepage.html", {'name':username, 'balance':total_balance})

    else:
        return redirect("www.google.com")
<!---- createentry.html ---->
<form action="{% url 'create_entry_form' %}" method="post">
    {% csrf_token %}
<div class="container register-form">
            <div class="form">
                <div class="note">
                    <p>Create Entry Form</p>
                </div>

                <div class="form-content">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <select name="expensetype" id="expensetype" class="form-control">
                                    <option value="expensetype">Select Expense Type</option>
                                    <option value="income">income</option>
                                    <option value="expense">expense</option>

                                </select>
                            </div>
                            <div class="form-group">
                                <input type="text" name="amount" id="amount" class="form-control" placeholder="Enter the Amount" value=""/>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <input type="text" name="entrydetails" id="entrydetails" class="form-control" placeholder="Enter the entry details" value=""/>
                            </div>
                            <div class="form-group">
                                <input type="text" name="entryusername" id="entryusername" class="form-control" placeholder="{{name}}" value=""/>

                            </div>
                        </div>
                    </div>
                    <button type="submit" class="btnSubmit">Submit</button>
                </div>
            </div>
        </div>
</form>
#models.py

from django.db import models
from django.contrib.auth.models import User

class IncomeExpense(models.Model):
    entry_type=models.CharField(max_length=100)
    amount=models.IntegerField()
    details=models.TextField()
    capture_date=models.DateField()
    username=models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.id}"


class UserBalance(models.Model):
    balance=models.IntegerField()
    username=models.ForeignKey(User, on_delete=models.CASCADE)

另外,为什么我会收到错误 Cannot assign "''": "IncomeExpense.username" must be a "User" instance.,如果我更改某些内容,我会收到另一个类似的错误。

我尝试在此方法中将用户名更改为username__username

entry=IncomeExpense.objects.create(entry_type=entry_type, amount=amount, details=details, capture_date=capture_date, username=entry_username)

【问题讨论】:

  • 你创建当前用户IncomeExpense ??
  • 是的,我做到了
  • 可能是什么错误?
  • 修复了一些损坏的英语。许多过时的“提前致谢”式短语已被删除。添加了语法高亮和内联代码格式。

标签: python-3.x django django-models django-views django-templates


【解决方案1】:

这里我们使用username字段来保存user id但是你传递了username。这是错误的。

def create_entry_form(request):
    if request.method=='POST':
        entry_type=request.POST.get("expensetype")
        amount=request.POST.get("amount")
        details=request.POST.get("entrydetails")
        capture_date=time.strftime('%Y-%m-%d')
        entry_username=request.POST.get("entryusername")

        entry=IncomeExpense.objects.create(entry_type=entry_type, amount=amount, details=details, capture_date=capture_date, username=request.user) #getting_error_in_this_line
        entry.save()
        user_balance = UserBalance.objects.filter(username=request.user).values_list('balance', flat=True)[0]
        if entry_type=="income":
            total_balance = user_balance + amount
        else:
            total_balance=user_balance - amount


        update_balance=UserBalance.objects.get(username=request.user)
        update_balance.balance=total_balance
        update_balance.save()
        return render(request, "homepage.html", {'name':request.user, 'balance':total_balance})

    else:
        return redirect("www.google.com")

【讨论】:

  • 这里我们将当前用户ID保存到IncomeExpense模型中
  • 我正在更新这个收入支出表中的余额值
  • 让我试试,让你知道
  • 我收到此错误,伙计无法分配“2”:“IncomeExpense.username”必须是“用户”实例。
  • 好的。我现在有空。
猜你喜欢
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多