I created a Child model which have a ForeignKey
instance 'parent' related to the Parent model. I wanted to associate a child to Post. For this, In my forms I created a ModelChoiceField
for 'parent' field. So to render this in my template, I make something as my below code. When i running the code, it raising an error:
TypeError : str returned non-string (type UUID).
I would appreciate helping me in fix this error.
Here's my code:
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"]
Template:
<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>
Update-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)
This may help you:
Use following code if you want to write something in your primary key field table on the basis of primary key accepting from Front End.
import uuid
uuidField = uuid.UUID(uuidField)
And If you want to request to database and send that output to FrontEnd the use it as str(uuidField) otherwise it will not get serialize. and will give you error.
Change it as follow:
def __str__(self):
return str(self.parent_id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With