Python / Django:TypeError:__str__返回非字符串(类型UUID)

时间:2016-07-26 12:12:55

标签: django django-models django-forms django-templates

我创建了一个Child模型,它具有与Parent模型相关的ForeignKey实例'parent'。我想把一个孩子和Post联系起来。为此,在我的表单中,我为“父”字段创建了ModelChoiceField。因此,要在我的模板中呈现此内容,我会将其作为下面的代码。当我运行代码时,它引发了一个错误:

  

TypeError: str 返回非字符串(类型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)

1 个答案:

答案 0 :(得分:5)

这可能会对您有所帮助:

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

import ET_Client
import pandas as pd


AggreateDF = pd.DataFrame()

try:

    debug = False
    stubObj = ET_Client.ET_Client(False, debug)

    print '>>>BounceEvents'
    getBounceEvent = ET_Client.ET_BounceEvent()
    getBounceEvent.auth_stub = stubObj    
    getResponse1 = getBounceEvent.get()
    ResponseResultsBounces = getResponse1.results
    Results_Message = getResponse1.message
    print "This is orginial " + str(Results_Message) 
    #print ResponseResultsBounces

    i = 1
    while (Results_Message == 'MoreDataAvailable'):
        if i > 5: break
        print Results_Message
        results1 = getResponse1.results
        i = i + 1
        ClientIDBounces = []
        partner_keys1 = []
        created_dates1 = []
        modified_date1 = []
        ID1 = []
        ObjectID1 = []
        SendID1 = []
        SubscriberKey1 = []
        EventDate1 = []
        EventType1 = []
        TriggeredSendDefinitionObjectID1 = []
        BatchID1 = []
        SMTPCode = []
        BounceCategory = []
        SMTPReason = []
        BounceType = []

        for BounceEvent in ResponseResultsBounces:
            ClientIDBounces.append(str(BounceEvent['Client']['ID']))
            partner_keys1.append(BounceEvent['PartnerKey'])
            created_dates1.append(BounceEvent['CreatedDate'])
            modified_date1.append(BounceEvent['ModifiedDate'])
            ID1.append(BounceEvent['ID'])
            ObjectID1.append(BounceEvent['ObjectID'])
            SendID1.append(BounceEvent['SendID'])
            SubscriberKey1.append(BounceEvent['SubscriberKey'])
            EventDate1.append(BounceEvent['EventDate'])
            EventType1.append(BounceEvent['EventType'])
            TriggeredSendDefinitionObjectID1.append(BounceEvent['TriggeredSendDefinitionObjectID'])
            BatchID1.append(BounceEvent['BatchID'])
            SMTPCode.append(BounceEvent['SMTPCode'])
            BounceCategory.append(BounceEvent['BounceCategory'])
            SMTPReason.append(BounceEvent['SMTPReason'])
            BounceType.append(BounceEvent['BounceType'])

        df1 = pd.DataFrame({'ClientID': ClientIDBounces, 'PartnerKey': partner_keys1,
                       'CreatedDate' : created_dates1, 'ModifiedDate': modified_date1, 
                       'ID':ID1, 'ObjectID': ObjectID1,'SendID':SendID1,'SubscriberKey':SubscriberKey1,
                       'EventDate':EventDate1,'EventType':EventType1,'TriggeredSendDefinitionObjectID':TriggeredSendDefinitionObjectID1,
                       'BatchID':BatchID1,'SMTPCode':SMTPCode,'BounceCategory':BounceCategory,'SMTPReason':SMTPReason,'BounceType':BounceType})
        #print(df1['ID'].max())
        AggreateDF = AggreateDF.append(df1)   
        print(AggreateDF)          
        #print df1
        df_masked1 = df1[(df1.EventDate > "2016-02-20") & (df1.EventDate < "2016-07-25")]

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

按以下方式更改:

import uuid
uuidField = uuid.UUID(uuidField)