Good day. The essence is this: there is an n-th number of objects with fields (text / numbers) and a file.

class Karto(models.Model): idname = models.IntegerField(default=0, blank=True, null=True) datecreated = models.DateTimeField(default=timezone.now()) ... file = models.FileField(upload_to='uploads', blank=True) 

I want to display data on one of the objects (view):

 def docsupdocs(request, idname): args = {} args['myq'] = Karto.objects.get(idname=idname) ... return render_to_response('self_docsup.html', args, context_instance=RequestContext(reqeust)) 

template:

 ... {{ myq.idname }} {{ myq.datecreated }} ... <a href="{{ myq.file }}">FILE</a> 

the problem is that the link does not open / download anything. link / downloads / file.txt I think the problem is in my crooked settings:

 MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'uploads') MEDIA_URL = '/uploads/' STATIC_URL = '/static/' STATICFILES_DIRS = [ ('static', 'C:/Python34/DocSup/static'), ] 

file lies in C: /Python34/DocSup/static/uploads/uploads/file.txt

still IMPORTANT moment: the way to media is not registered in url ... did as in documentation

 urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() 

but nothing worked for me and I removed ... QUESTION. Gentlemen, what do I need to add in order for the link to open the document?

  • it seems to me, or the file should lie not C: / Python34/DocSup/static/uploads/uploads/file.txt, but C: / Python34/DocSup/static/uploads/file.txt - Kamo Petrosyan

1 answer 1

You have a small inaccuracy:

 file = models.FileField(upload_to='uploads', blank=True) 

MEDIA_ROOT points to C: / Python34 / DocSup / static / uploads / Plus another uploads / is added, if the relative path is specified in the upload_to. Accordingly, everything is loaded into C: / Python34 / DocSup / static / uploads / uploads /

And the link is {{myq.file.url}}.

 ... {{ myq.idname }} {{ myq.datecreated }} ... <a href="{{ myq.file.url }}">FILE</a> 

Then get /uploads/uploads/file.txt

Accordingly, correct the model like this:

 class Karto(models.Model): idname = models.IntegerField(default=0, blank=True, null=True) datecreated = models.DateTimeField(default=timezone.now()) ... file = models.FileField(upload_to='', null=True, blank=True) 

Or so:

 from django.conf import settings class Karto(models.Model): idname = models.IntegerField(default=0, blank=True, null=True) datecreated = models.DateTimeField(default=timezone.now()) ... file = models.FileField(upload_to=settings.MEDIA_ROOT, blank=True)