Home > Software engineering >  saved data not visible in CRUD using serializers and foreign keys
saved data not visible in CRUD using serializers and foreign keys

Time:07-13

I am doing CRUD where I am using foreign keys and serializers as it is my task and I am new to serializers

I am trying to update my data however the saved data of categories,sub_categories,color and size arent showing up isntead are showing up as blank as shown below enter image description here

below are all the serializers

class CategoriesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Categories
        fields = "__all__"
        extra_kwargs = {'category_name': {'required': False}}


class ColorsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Colors
        fields = "__all__"

class POLLSerializer(serializers.ModelSerializer):
    # categories = serializers.StringRelatedField(many=False)
    # sub_categories = serializers.StringRelatedField(many=False)
    # color = serializers.StringRelatedField(many=False)
    # size = serializers.StringRelatedField(many=False)
    class Meta:
        model = Products
        fields = "__all__"


class SizeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Size
        fields = "__all__"


class SUBCategoriesSerializer(serializers.ModelSerializer):
    class Meta:
        model = SUBCategories
        fields = "__all__"

models

class Products(models.Model):
    categories = models.ForeignKey(Categories,on_delete=models.CASCADE)
    sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE)
    color = models.ForeignKey(Colors,on_delete=models.CASCADE)
    size = models.ForeignKey(Size,on_delete=models.CASCADE)
    # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True)
    title = models.CharField(max_length=50)
    price = models.CharField(max_length=10)
    sku_number = models.CharField(max_length=10)
    product_details = models.CharField(max_length=300)
    quantity = models.IntegerField(default=0)
    isactive = models.BooleanField(default=True)

class Categories(models.Model):
    #made changes to category_name for null and blank
    category_name = models.CharField(max_length=20)
    category_description = models.CharField(max_length=20)
    isactive = models.BooleanField(default=True)
    
    def __str__(self):
        return self.category_name
class Colors(models.Model):
    color_name = models.CharField(max_length=10)
    color_description = models.CharField(max_length=10)
    isactive = models.BooleanField(default=True)

    def __str__(self):
        return self.color_name
class Size(models.Model):
    size_name = models.CharField(max_length=10)
    size_description = models.CharField(max_length=20)
    isactive = models.BooleanField(default=True)

    def __str__(self):
        return self.size_name
class SUBCategories(models.Model):
    category_name = models.ForeignKey(Categories, on_delete=models.CASCADE)
    sub_categories_name = models.CharField(max_length=20)
    sub_categories_description = models.CharField(max_length=20)
    isactive = models.BooleanField(default=True)

    def __str__(self):
        return self.sub_categories_name

update function

def update(request,id):
    if request.method == 'GET':
        print('GET',id)
        edit_products = SUBCategories.objects.filter(id=id).first()
        s= SUBCategoriesSerializer(edit_products)
        category_dict = Categories.objects.filter(isactive=True)
        category = CategoriesSerializer(category_dict, many=True)
        sub_category_dict = SUBCategories.objects.filter(isactive=True)
        sub_category = SUBCategoriesSerializer(sub_category_dict,many=True)
        color_dict = Colors.objects.filter(isactive=True)
        color = ColorsSerializer(color_dict,many=True)
        size_dict = Size.objects.filter(isactive=True)
        size = SizeSerializer(size_dict,many=True)
        hm = {"context": category.data,"sub_context":sub_category.data,"color_context":color.data,"size_context":size.data,"SUBCategories":s.data}
        return render(request,'polls/product_edit.html',hm)
    else:
        print('POST',id)
        editproducts = {}
        d = Products.objects.filter(id=id).first()
        if d:
            editproducts['categories']=request.POST.get('categories')
            editproducts['sub_categories']=request.POST.get('sub_categories')
            editproducts['color']=request.POST.get('color')
            editproducts['size']=request.POST.get('size')
            editproducts['title']=request.POST.get('title')
            editproducts['price']=request.POST.get('price')
            editproducts['sku_number']=request.POST.get('sku_number')
            editproducts['product_details']=request.POST.get('product_details')
            # print(editsubcategories)
            form = SUBCategoriesSerializer(d,data= editproducts)
            if form.is_valid():
                form.save()
                print("form data",form.data)
                print('form error',form.errors)
                messages.success(request,'Record Updated Successfully...!:)')
                return redirect('polls:show')
            else:
                print(form.errors)
                return redirect("polls:show")

html page of product edit

<td>Categories</td>
<td>
                            
   <input name="categories" id="CATEGORIES" placeholder="enter categories" list="Categories" value="{{Categories.category_name}}">
   <datalist id="Categories">
      {% for c in context %}
          <option value="{{c.id}}">{{c.category_name}}</option>
      {% endfor %}
   </datalist>
 </td>
<td>Sub-Categories</td>
 <td>
   <input name="sub_categories" id="SUBCATEGORIES" placeholder="enter subcategories" list="SUBCategories" value="{{SUBCategories.sub_categories_name}}">
   <datalist id="SUBCategories">
    {% for c in sub_context %}
      <option value="{{c.id}}">{{c.sub_categories_name}}</option>
    {% endfor %}
   </datalist>
</td>

<tr>
<td>Colors</td>
<td><input type="text" name="color" value="{{Colors.color_name}}"></td>
</tr>

<tr>
    <td>Size</td>
    <td><input type="text" name="size" value="{{Size.size_name}}"></td>
</tr>

where am I going wrong in the code whichis causing the problem?

CodePudding user response:

I would try nesting serializers, like so:

class POLLSerializer(serializers.ModelSerializer):
    categories = CategoriesSerializer(many=True)
    sub_categories = SUBCategoriesSerializer(many=True)
    color = ColorsSerializer()
    size = SizeSerializer()

    class Meta:
        model = Products
        fields = ["categories", "sub_categories", "color", "size", ...]

Add any other fields you need to the fields list. You may be able to use __all__ but in case that does not work, try adding all the properties you need to the fields list.

  • Related