1

i have a django REST API with a models.ImageField(), i can upload photos just fine from django itself, my problem is when im trying to do it from angular.

.html

<div class="form-group">
 <label for="usr">Upload your new photo(Optional):</label> <input type="file"  accept=".jpg,.png,.jpeg" (change)="attachFile($event)">
 <br>
 <img src="{{imageSrc}}"   height="250" weight="250" alt="Image preview..." />
</div>

component.ts

Update(form){
  let body = {
    house: 3,
    photourl: this.imageSrc
  }
  console.log(this.imageSrc)
  this.http.Post('http://127.0.0.1:8000/api/photos', body).subscribe( res => console.log(res))
  console.log(form)
}

attachFile(event) : void {
    var reader = new FileReader();
    let _self = this;

    reader.onload = function(e) {
      _self.imageSrc = reader.result;
    };
    reader.readAsDataURL(event.target.files[0]);
   }

error is this.imageSrc is not a file, how should i get past this? What data do I need to send to an ImageField()

1 Answer 1

1

https://github.com/Hipo/drf-extra-fields Well godlike library :D!

class HouseImSerializer(serializers.ModelSerializer):
    image = Base64ImageField(required=False)

    class Meta:
        model = tedbnbhouseimages
        fields = ('house', 'image', 'photo')

    def create(self, validated_data):
        house = validated_data['house']
        if not validated_data['photo']:
            photo = validated_data['image']
        else:
            photo = validated_data['photo']
        houseimage = tedbnbhouseimages(
            house = house,
            photo = photo,
        )
        houseimage.save()
        return houseimage

photo = Imagefield from models.py, photo doesnt need to be on fields but i keep it for quick creation through DRF !

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.