gpt4 book ai didi

django - Python/Django : TypeError : __str__ returned non-string (type UUID)

转载 作者:行者123 更新时间:2023-12-04 20:02:54 28 4
gpt4 key购买 nike

我创建了一个子模型,它有一个 ForeignKey与父模型相关的实例“父”。我想将一个 child 与 Post 联系起来。为此,在我的表单中,我创建了一个 ModelChoiceField对于“父”字段。所以为了在我的模板中呈现这个,我做了一些作为我下面的代码。当我运行代码时,它引发了一个错误:

TypeError : str returned non-string (type UUID).



我将不胜感激帮助我解决此错误。

这是我的代码:

模型.py:
class Parent(models.Model):

parent_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
from1 = models.CharField(max_length=20)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

objects = ParentManager()

def __str__(self):
return self.parent_id

def get_absolute_url(self):
return reverse("detail", kwargs={"id": self.parent_id})


class Child(models.Model):

child_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
parent = models.ForeignKey(Parent, default=uuid.uuid4, related_name='childs' )
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True, unique=False)
amount = models.IntegerField()

def get_absolute_url(self):
return reverse("accept_child", kwargs={"child_id": self.child_id})

def __unicode__(self):
return self.amount

def __str__(self):
return self.amount

表格.py:
 class ChildForm(forms.ModelForm):

parent = forms.ModelChoiceField(queryset= Parent.objects.all(), label="Parent", widget=forms.RadioSelect(), initial=0)
amount = forms.IntegerField(help_text='Place the child for a Parent')

def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(ChildForm, self).__init__(*args, **kwargs)
self.fields['parent'].queryset = Parent.objects.all()

class Meta:
model = Child
fields = ["amount"]

模板:
<td > {% for choice in form.parent.field.choices %} 
<li><input type="radio" name="{{ choice.parent }}" value="{{ choice.0 }}" />
<label for="">{{choice.1}}</label></li>
{% endfor %}</td>

更新 1:

View .py:
def live_bid_truck(request):

form = ChildForm(request.POST or None)

if form.is_valid():
child = form.save(commit=False)

print(form.cleaned_data.get("amount"))
child.user = request.user # YOU SET THE USER
child.parent = ?? # I DON'T HOW TO SET THE PARENT HERE,


child.save()


print(child.parent.id)

最佳答案

这可能会帮助您:

如果您想根据从前端接受的主键在主键字段表中写入一些内容,请使用以下代码。

import uuid
uuidField = uuid.UUID(uuidField)

如果您想请求数据库并将该输出发送到 FrontEnd,请将其用作 str(uuidField) 否则它将不会被序列化。并且会给你错误。

更改如下:
def __str__(self):
return str(self.parent_id)

关于django - Python/Django : TypeError : __str__ returned non-string (type UUID),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38589595/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com