我創建了一個子模型,其中有一個ForeignKey
與Parent模型相關的實例「父」。我想把一個孩子與Post相關聯。爲此,在我的表格中,我爲「父」字段創建了一個ModelChoiceField
。所以爲了在我的模板中渲染這個,我做了一些如下面的代碼。當我運行的代碼,它引發一個錯誤:Python/Django:TypeError:__str__返回的非字符串(類型UUID)
TypeError : str returned non-string (type UUID).
我希望能幫助我解決這個錯誤。
這裏是我的代碼:
Models.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
forms.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:
views.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)
你需要使用'self.fields [ '父'] =查詢集Parent.objects.all()'在'ChildForm'。注意'()'。 –
謝謝。我錯過了括號。現在,我收到一個錯誤:__str__返回非字符串(類型UUID),因爲我使用UUID作爲主鍵。我可以知道我爲什麼得到這個嗎? – sumanth
將其用作str(uuid字段)。 –