Cannot assign "'4'": "Element.value_code" must be a "Value" instance

Issue

I’m trying to save element.value_code, but this error occurs. If I get the value_code on the getlist, my mission will be over. How should I correct this error? I’d really appreciate it if you could let me know.

Error:

Cannot assign "'4'": "Element.value_code" must be a "Value" instance.

models.py

There were only models related to Value and Element, but we added all models to help you understand why option_code and designated_code exist.

class Option(models.Model):
    option_code = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['option_code']

class Value(models.Model):
    value_code = models.AutoField(primary_key=True)
    option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code')
    product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
    name = models.CharField(max_length=32)
    extra_cost = models.IntegerField()

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['value_code']

class Designated(models.Model):
    designated_code = models.AutoField(primary_key=True)
    product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code')
    price = models.IntegerField()
    rep_price = models.BooleanField(default=True)

    class Meta:
        ordering = ['designated_code']

    def __str__(self):
        return str(self.designated_code)

class Element(models.Model):
    element_code = models.AutoField(primary_key=True)
    designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, db_column='designated_code')
    value_code = models.ForeignKey(Value, on_delete=models.CASCADE, db_column='value_code', null=True, blank=True)

    class Meta:
        ordering = ['element_code']

    def __str__(self):
        return str(self.element_code)

views.py

if request.method == "POST":
    form = ElementForm(request.POST)

    if form.is_valid():
        for value_code2 in request.POST.getlist('value_code2'):
            element = Element()
            element.designated_code = Designated.objects.get(product_code=id)
            element.value_code = value_code2
            element.save()

    else:
        element = Element()
        element.designated_code = Designated.objects.get(product_code=id)
        element.value_code = None
        element.save()

forms.py

class ElementForm(forms.Form):
    value_code2 = forms.ModelChoiceField(error_messages={'required': "옵션을 선택하세요."}, label="옵션", queryset=Value.objects.all())

Solution

You are sending PK or ID to your url.

For making relation between those sent PKs and your Element model, you should give Element an object of Value, not its PK

And when you use for value_code2 in request.POST.getlist('value_code2'), value_code2 is PK and it’s wrong

Your solution can be that after passing data to ElementForm, this returns you some cleaned_data if form.is_valid(). And in that cleaned_data there should be Value object:

...
if form.is_valid():
    element = Element()
    element.designated_code = Designated.objects.get(product_code=id)
    element.value_code = form.cleaned_data['value_code2']
    element.save()

Read about cleaned_data in https://docs.djangoproject.com/en/3.2/ref/forms/api/#django.forms.Form.cleaned_data

Answered By – Amin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published