[英]Allow users to download files directly django
In the TrainerProfileModel I have file field called cv.在 TrainerProfileModel 中,我有一个名为 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:模型.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>
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.我们需要直到 django 关于我们的媒体图像,所以我们通过from django.conf import settings
urls.py 中的设置,并通过此代码if settings.DEBUG: urlpatterns += urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我们直到 django 关于我们的媒体图像,不要忘记通过MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'
添加 Media root 和 Media URL最后我们添加图像。 url in src attribute of image in our html page it will display the image. url在我们的 html 页面中图像的 src 属性中它将显示图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.