Django 从对象创建模型实例

huangapple go评论61阅读模式
英文:

Django Create Model Instance from an Object

问题

我正在开发一个Django每日储蓄应用程序,其中员工用户可以创建客户账户,并且在客户账户列表中有一个存款链接,员工用户可以在其中添加客户存款。
问题在于,在获取到客户ID并传递到客户存款视图后,我想从该ID获取客户详细信息并创建他的存款,但每次尝试时我看到以下错误:无法分配"django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor object at 0x00000129FD8F4910": "Deposit.customer"必须是"Profile"实例
以下是我的模型:

class Profile(models.Model):
    customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    surname = models.CharField(max_length=20, null=True)
    othernames = models.CharField(max_length=40, null=True)
    gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
    address = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=11, null=True)
    image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to='profile_images')
    def __str__(self):
        return f'{self.customer.username}-Profile'

class Account(models.Model):
    customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    account_number = models.CharField(max_length=10, null=True)
    date = models.DateTimeField(auto_now_add=True, null=True)
    def __str__(self):
        return f'{self.customer} - Account No: {self.account_number}'

class Deposit(models.Model):
    customer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
    acct = models.CharField(max_length=6, null=True)
    staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    deposit_amount = models.PositiveIntegerField(null=True)
    date = models.DateTimeField(auto_now_add=True)
    def get_absolute_url(self):
        return reverse('create_account', args=[self.id])
    def __str__(self):
        return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}'

请忽略任何缺失的表单,并帮助我从上述的客户账户ID创建一个Profile实例。谢谢。

英文:

I am working on a Django Daily Saving App where Staff User can create Customer Account, and from the list of the Customer Accounts there is link for Deposit where staff user can add customer deposit.
The issue is that after getting the customer id to the customer deposit view, I want to create get the customer details from the ID and create his deposit but anytime I try it I see: Cannot assign "<django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor object at 0x00000129FD8F4910>": "Deposit.customer" must be a "Profile" instance
See below my Models:

class Profile(models.Model):
    customer = models.OneToOneField(User, on_delete=models.CASCADE, null = True)
    surname = models.CharField(max_length=20, null=True)
    othernames = models.CharField(max_length=40, null=True)
    gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True)
    address = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=11, null=True)

    image = models.ImageField(default=&#39;avatar.jpg&#39;, blank=False, null=False, upload_to =&#39;profile_images&#39;, 

)
    def __str__(self):
        return f&#39;{self.customer.username}-Profile&#39;


class Account(models.Model):
    customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    account_number = models.CharField(max_length=10, null=True)
    date = models.DateTimeField(auto_now_add=True, null=True) 

    def __str__(self):
        return f&#39; {self.customer} - Account No: {self.account_number}&#39;

class Deposit(models.Model):
    customer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
    acct = models.CharField(max_length=6, null=True)
    staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    deposit_amount = models.PositiveIntegerField(null=True) 
    date = models.DateTimeField(auto_now_add=True)  

    def get_absolute_url(self):
        return reverse(&#39;create_account&#39;, args=[self.id])

    def __str__(self):
        return f&#39;{self.customer} Deposited {self.deposit_amount} by {self.staff.username}&#39;

Here are my views:

def create_account(request): 
    if searchForm.is_valid():
        #Value of search form
        value = searchForm.cleaned_data[&#39;value&#39;]
        #Filter Customer by Surname, Othernames , Account Number using Q Objects
        user_filter = Q(customer__exact = value) | Q(account_number__exact = value)
        #Apply the Customer Object Filter
        list_customers = Account.objects.filter(user_filter) 
    
    else:
        list_customers = Account.objects.all()

    context = {
        
        
        &#39;customers&#39;:customers,
        
        }
    return render(request, &#39;dashboard/customers.html&#39;, context)

def customer_deposit(request, id):
    try:
        #Check the Customer ID in DB
        customer = Account.objects.get(id=id)
        #Customer Account
        acct = Account.account_number
        profile = Profile.objects.get(customer=customer.customer.id)
        profile = User.profile
        
    except Account.DoesNotExist:
        messages.error(request, &#39;Customer Does Not Exist&#39;)
        return redirect(&#39;create-customer&#39;)
    else:
if request.method == &#39;POST&#39;:
            #Deposit Form
            form = CustomerDepositForm(request.POST or None)
            
            if form.is_valid():
                #Get  Deposit Details for form variable
                amount = form.cleaned_data[&#39;deposit_amount&#39;]
                
                #Set Minimum Deposit
                minimum_deposit = 100
                #Check if Customer Deposit is Less than the Minimum Deposit
                if amount &lt; minimum_deposit:
                    messages.error(request, f&#39;N{amount} is less than the Minimum Deposit of N{minimum_deposit}&#39;)
                else:
                    #Add Customer Deposit
                    credit_acct = Deposit.objects.create(customer=profile, acct=acct, staff=user, deposit_amount=amount)
                    #Save the Customer Deposit
                    credit_acct.save()
                
                    

                    context.update(  {
                    &#39;amount&#39;:amount,
                    
                    &#39;count_accounts&#39;:count_accounts,
                    })
                    
                    messages.success(request, f&#39;N{amount} Deposited to Account {acct} Successfully.&#39;)
                    
                    return render(request, &#39;dashboard/deposit_slip.html&#39;, context)
                
        else:
            form = CustomerDepositForm()
        context.update(  {
                
                &#39;customer&#39;:customer,
                
                })
        return render(request, &#39;dashboard/deposit.html&#39;, context)

Here is my Template code the use of context.

{% for customer in customers %}  
              &lt;tr&gt;
                &lt;td&gt;{{ forloop.counter }}&lt;/td&gt;
                &lt;td&gt;{{ customer.account_number  }}&lt;/td&gt; 

                {% if customer.customer.profile.surname == None %}

                &lt;td&gt; &lt;a class=&quot;btn btn-danger&quot; href=&quot; {% url &#39;update-customer&#39; customer.customer.id %} &quot;&gt;Update Customer Details.&lt;/a&gt; &lt;/td&gt;

                {% else %}
                
                &lt;td&gt;{{ customer.customer.profile.surname }} {{ customer.customer.profile.othernames }}&lt;/td&gt;
                
                &lt;td&gt;{{ customer.customer.profile.phone }}&lt;/td&gt;

                &lt;td&gt;&lt;a class=&quot;btn btn-success btn-sm&quot; href=&quot;{% url &#39;account-statement&#39; customer.customer.id %}&quot;&gt;Statement&lt;/a&gt;&lt;/td&gt;
                
                
                
                &lt;td&gt;&lt;a class=&quot;btn btn-danger btn-sm&quot; href=&quot;{% url &#39;dashboard-witdrawal&#39; customer.id  %}&quot;&gt;Withdraw&lt;/a&gt;&lt;/td&gt;
                


                &lt;th scope=&quot;row&quot;&gt;&lt;a class=&quot;btn btn-success btn-sm&quot; href=&quot;{% url &#39;create-deposit&#39; customer.id %}&quot;&gt;Deposit&lt;/a&gt;&lt;/th&gt;
                {% endif %}
                
                
              &lt;/tr&gt;
              {% endfor %}  

Please ignore any missing form and help on how to make a Profile instance from the Customer Account ID as shown above. thanks

答案1

得分: 0

问题在于您在custom_deposite函数中,将外键字段传递给Deposit.objects.create而不是传递实例,并尝试删除以下内容:

profile = User.profile

另外,还有一处错误在于以下这行:

acct = Account.account_number

应该改为:

acct = customer.account_number
英文:

the problem is that you pass the foreign key field instead of the instance to your Deposit.objects.create in your custom_deposite function and try removing

profile = User.profile

also there is another error in line

acct = Account.account_number

it should be

acct = customer.account_number

huangapple
  • 本文由 发表于 2023年2月8日 19:32:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定