Allow users to download files directly django

2019-08-22 23:34发布

问题:

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>

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

回答1:

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