0

How to Create Multiple Experinces in Django

def post(self, request): associated_company_id = request.data.get('associated_company') if associated_company_id is not None: associated_company = get_object_or_404(ContactCompany, pk=associated_company_id) #print(associated_company.created_by.refrence_id_id,request.user.id) if associated_company.created_by.refrence_id_id != request.user.id: raise ValidationError("Associated company does not belong to the logged-in user.") # Validate email field presence #emails_data = request.data.get('emails', [])

    contact_data = request.data
    addresses_data = contact_data.pop('addresses', [])
    emails_data = contact_data.pop('emails', [])
    """if not emails_data:
        raise ValidationError({'msg':"Email field is required."})"""
    mobiles_data = contact_data.pop('mobiles', [])
    """if not mobiles_data:
        raise ValidationError({'msg':"Mobile field is required."})"""
    landlines_data = contact_data.pop('landlines', [])
    relationships_data = contact_data.pop('relationships', [])
    significant_dates_data = contact_data.pop('significant_dates', [])
    tags_data = contact_data.pop('tags', [])
    # Process photo upload
    encoded_image = request.data.get('photo')
    if encoded_image:
        try:
            decoded_image = base64.b64decode(encoded_image)
            contact_data['photo'] = ContentFile(decoded_image, name='contact_photo.jpg')
        except Exception as e:
            return Response({'success': False, 'msg': 'Failed to decode and process photo upload.', 'status': status.HTTP_400_BAD_REQUEST})
    contact_serializer = ContactSerializer(data=contact_data)
    employee = Employee.objects.get(email=request.user.email)
    if contact_serializer.is_valid():
        
        existing_contacts_count = Contact.objects.filter(associated_company=associated_company_id).count()

        # If there are no existing contacts, set the primary_contact field to True
        if existing_contacts_count == 0:
            contact_serializer.validated_data['primary_contact'] = True
        contact = contact_serializer.save(created_by=employee)
        for address_data in addresses_data:
            address_data['contact'] = contact.id
            address_serializer = ContactAddressSerializer(data=address_data)
            if address_serializer.is_valid():
                address_serializer.validated_data['contact_id'] = contact.id
                address_serializer.validated_data['address_type_id'] = address_data['address_type']
                address_serializer.save()
            else:
                contact.delete()  # Delete the contact if address serializer is not valid
                return Response({'success':False,'msg':address_serializer.errors,'status':status.HTTP_400_BAD_REQUEST}, status=status.HTTP_400_BAD_REQUEST)
        # Create emails
        #emails_data = json.loads(emails_data)
        for email_data in emails_data:
            email_data['contact'] = contact.id
            email_serializer = ContactEmailSerializer(data=email_data)
            if email_serializer.is_valid():
                email_serializer.save()
            else:
                contact.delete()  # Delete the contact if address serializer is not valid
                return Response({'success':False,'msg':email_serializer.errors,'status':status.HTTP_400_BAD_REQUEST}, status=status.HTTP_400_BAD_REQUEST)

        # Create mobiles
        for mobile_data in mobiles_data:
            mobile_data['contact'] = contact.id
            mobile_serializer = MobileSerializer(data=mobile_data)
            if mobile_serializer.is_valid():
                mobile_serializer.save()
            else:
                contact.delete()  # Delete the contact if address serializer is not valid
                return Response({'success':False,'msg':mobile_serializer.errors,'status':status.HTTP_400_BAD_REQUEST}, status=status.HTTP_400_BAD_REQUEST)

        # Create landlines
        for landline_data in landlines_data:
            if landline_data['landline_type'] is not None and landline_data['landline_type'] != '':
                landline_data['contact'] = contact.id
                landline_serializer = LandlineSerializer(data=landline_data)
                if landline_serializer.is_valid():
                    landline_serializer.save()
                else:
                    contact.delete()  # Delete the contact if address serializer is not valid
                    return Response({'success':False,'msg':landline_serializer.errors,'status':status.HTTP_400_BAD_REQUEST}, status=status.HTTP_400_BAD_REQUEST)

        # Create relationships
        for relationship_data in relationships_data:
            if relationship_data['relationship_type'] is not None and relationship_data['relationship_type'] != '':
                relationship_data['contact'] = contact.id
                relationship_serializer = RelationshipSerializer(data=relationship_data)
                if relationship_serializer.is_valid():
                    relationship_serializer.save()
                else:
                    contact.delete()  # Delete the contact if address serializer is not valid
                    return Response({'success':False,'msg':relationship_serializer.errors,'status':status.HTTP_400_BAD_REQUEST}, status=status.HTTP_400_BAD_REQUEST)

        # Create significant dates
        for significant_date_data in significant_dates_data:
            if significant_date_data['date_type'] is not None and significant_date_data['date_type'] != '':
                significant_date_data['contact'] = contact.id
                significant_date_serializer = SignificantDateSerializer(data=significant_date_data)
                if significant_date_serializer.is_valid():
                    significant_date_serializer.save()
                else:
                    contact.delete()  # Delete the contact if address serializer is not valid
                    return Response({'success':False,'msg':significant_date_serializer.errors,'status':status.HTTP_400_BAD_REQUEST}, status=status.HTTP_400_BAD_REQUEST)

        # Create Tags
        for tag_data in tags_data:
            if tag_data['name'] is not None and tag_data['name'] != '':
                tag_data['contact'] = contact.id
                tag_serializer = ContactTagsSerializer(data=tag_data)
                if tag_serializer.is_valid():
                    tag_serializer.save()
                else:
                    contact.delete()  # Delete the contact if address serializer is not valid
                    return Response({'success':False,'msg':tag_serializer.errors,'status':status.HTTP_400_BAD_REQUEST}, status=status.HTTP_400_BAD_REQUEST)
        # Repeat similar logic for other nested serializers

        return Response({'success':True,'data':contact_serializer.data,'msg':'Contact details created successfully','status':status.HTTP_200_OK}, status=status.HTTP_201_CREATED)
        #{'success':True,'data':employee_serializer.data,'msg':'User successfully registed','status':status.HTTP_200_OK}, status=status.HTTP_201_CREATED
    else:
        return Response({'success':False,'msg':contact_serializer.errors,'status':status.HTTP_400_BAD_REQUEST}, status=status.HTTP_400_BAD_REQUEST)

I have a contact API how to upload a image use row data.

1 Answer 1

0

I think that there are many things gone wrong here. If I understand well, you have users that can have multiple experiences? If that is true, then the user is a master model and experiences is a detail model, and the relation should go the opposite way (experiences have relation to the user model). There are other possibilities, but this is the easiest one.

Than, you are not utilising the django templateing in it's full potential. There is no need to assign all that fields in views, most of this can be accomplished directly.

In the end, if you wish to add on template multiple instances of the detail model (experiences) on the same page, you would probably need to take a look at the formsets that can easily accomplish this.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.