1

In the TrainerProfileModel I have file field called cv. I want to allow users to download the file directly when clicking on the link. Could you provide any ways to implement this?

models.py:

class TrainerProfile(models.Model):
 user = models.OneToOneField(User, on_delete=models.CASCADE, 
 null=True, related_name='trainer_profile')
 profile_picture = models.ImageField(blank=True)
 phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone 
 number must be entered in the format: '+999999999'. Up to 15 digits 
 allowed.")
 mobile_number = models.CharField(validators=[phone_regex], 
 max_length=17, blank=True)
 location = models.CharField(max_length=200,null=True,blank=True)
 gender = models.CharField(choices=GENDER_CHOICES,max_length=150, 
 blank=True)
 cv = models.FileField(blank=True)
 approval=models.BooleanField(default=False)

 def __str__(self):
    return self.user.username

In my template:

<li class="list-group-item">
  <b>Download CV</b>
  <a class="pull-right">{{ trainer.cv }}</a>
</li>
Sergey
  • 995
  • 4
  • 14
  • 33
Mohit Harshan
  • 1,916
  • 1
  • 18
  • 41
  • 1
    Yes, use the `href` attribute of the `a` tag with a value of `{{ trainer.cv.url }}`. – Selcuk Nov 02 '18 at 06:00
  • 2
  • 1
    Most likely it will not work for images, pdf and some video formats. For that you need to create a custom url for downloading files and add proper headers to urls. If not working see this question for details https://stackoverflow.com/questions/15246661/downloading-the-fileswhich-are-uploaded-from-media-folder-in-django-1-4-3 – Vaibhav Vishal Nov 02 '18 at 06:05

2 Answers2

0

As mentioned in comments use trainer.cv.url instead but also there is other approach for this too, take a look at it here.

GoodLuck

Glyphack
  • 876
  • 9
  • 20
0

We need to till django about our media images so we import the settings in urls.py by from django.conf import settings and by this code if settings.DEBUG: urlpatterns += urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) we till django about our media images , DONOT forget to add Media root and Media URL by MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and finally we we add image.url in src attribute of image in our html page it will display the image.