I need an image upload directive, here is how my code looks like:
# Model
class transporter(models.Model):
company_name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
image = models.FileField(upload_to=upload_path,blank=True, null=True)
def upload_path(self, filename):
return 'photos/%s/%s' % (self.company_name, filename)
# Serializer
class transporterSerializer (serializers.HyperlinkedModelSerializer):
username = serializers.Field(source='username.username')
class Meta:
model = transporter
fields = ('id','company_name','address','image')
it works with only django rest framework but i get Bad request error if I post the transporter model with angularjs. I need to upload the image and set the image field with the image URL. thank you
I'll share my experience with file upload using angular and drf.
Step 1:
Use a file model directive when binding your file input to an angular model. Im using the one below in several projects which does the trick for me. I got it from this blogpost by Jenny Louthan.
Used on a file input:
Step 2:
Create a formData object in your controller or service which handles the post. This is can be done by first initiating a new formData object. Then looping through your angular object and setting all its attributes to that formData object.
If done in the controller this can be done like this:
(I'm using lodash for the _.each loop, but go with whatever suits you)
Step 3:
Use angulars $http to post formData object to your url endpoint and handle the success request as you please!