how to pass data in array to post method in angular and django?

198 Views Asked by At

I am trying to pass a list of student IDs but it is not working.

from angular I am passing data as follows

let noticeData = this.announceForm.value;
if (noticeData.students.includes('all')){
    noticeData.students = noticeData.students.filter((s) => s != 'all')
}
noticeData.students = JSON.stringify(noticeData.students);

rest call

var formData = new FormData();
for (var key in noticeData) {
    formData.set(key, noticeData[key]);
}

this._rest.one("/classwork/notices/")
      .post('', formData)
      .toPromise()
      .then((classworks) => {
      }, (error) => {
        console.log("ERROR SENDING ANNOUNCEMENT ", error);
        this.alert = {
          type   : "error",
          message: "Something went wrong, please try again."
        }
      });

}

from django i am reading and trying to store data as

Below is the to_internal_value method which I have overridden.

def to_internal_value(self, data):
    tempdict = data.copy()
    tempdict['students'] = json.loads(data['students'])
    data = tempdict
    return super(NoticesSerializer, self).to_internal_value(data)

views.py

class ClassworkView(APIView):
def get(self, request, format=None):
    notices = ClassworksFilter(request.query_params, queryset=Notice.objects.all()).qs
    materials = ClassworksFilter(request.query_params, queryset=Material.objects.all()).qs
    assignments = ClassworksFilter(request.query_params, queryset=Assignment.objects.all()).qs
    queryset = sorted(
        chain(notices, materials, assignments),
        key=lambda instance: instance.create_date
    )

    model_serializers = {
        'notice': NoticesSerializer,
    }
    classworks = []
    for instance in queryset:
        serializer = model_serializers[instance._meta.model_name]
        data = serializer(instance).data
        data['classwork_type'] = instance._meta.model_name
        classworks.append(data)

    page_number = request.query_params.get('page', 1)
    page_size = request.query_params.get('page_size', 20)
    page = Paginator(classworks, per_page=page_size).get_page(page_number)

    base_url = f'{request.scheme}://{request.get_host()}{reverse("classworks")}'
    params = [f'{k}={v}' if k!='page' else None for k,v in request.query_params.items()]
    indx = 0
    for param in params:
        if param==None:
            params.pop(indx)
        indx+=1
    params = '&'.join(params)
    next = f'{base_url}?page={page.next_page_number()}&{params}' if page.has_next() else None
    prev = f'{base_url}?page={page.previous_page_number()}&{params}' if page.has_previous() else None

    response = {
        'count': len(classworks),
        'next': next,
        'previous': prev,
        'results': page.object_list
    }
    return Response(response)

here is serializer.py

class NoticesSerializer(serializers.ModelSerializer):
class Meta:
    model = Notice
    fields = '__all__'

def to_representation(self, instance):
    representation = super(NoticesSerializer, self).to_representation(instance)
    try:
        representation['classroom'] = ClassroomsSerializer(instance.classroom, context=self.context).data
        students = StudentsSerializer(instance.students, many=True, context=self.context).data
        for student in students:
            student['classroom'] = student['classroom']['id']
        representation['students'] = students
    except Exception as error:
        print("ERROR SETTING REPRESENTATION FOR NOTICE SERIALIZER", error)
    return representation

here is the models.py

class Notice(Classwork):
file = models.FileField(upload_to='classworks/attachments', blank=True, null=True)
link = models.URLField(blank=True, null=True)
description = models.TextField()

class Meta(BaseModel.Meta):
    db_table = 'ec_notice'

but it always returns the same error

{students: [“Incorrect type. Expected pk value, received list.”]}

here the data I am posting by form data

data passing

0

There are 0 best solutions below