I have a model called Advertisement. This model has text field, title field, and file field.
I am successfully saving all 3 of these fields into the model.
Now I need to show them in template. My vision is:
ads = Advertisement.objects.all()
return render_to_response('page.html', {'ads':ads},context_instance=RequestContext(request))
and in my page.html:
{% for each_ad in ads %}
<p>{{each_ad.title}}</p>
<p>{{each_ad.text}}</p>
<p><a href="/ads/{{each_ad.file_pdf}}>{{each_ad.file_pdf.name}}</a></p>
{% endfor %}
Does this seem right? If not, please show me the way so I can learn. Thanks!
Whether the PDF link downloads depends on the browser of the user.
Adding target="_blank" will open the pdf in a new window/tab though:
<p>{{each_ad.file_pdf.name}}</p>
To ensure that it always downloads in every environment is more difficult, you would need to set your .htaccess (if you're using apache, per something like this: Force a file or image to download using .htaccess) or force it as an attachment in producing the PDF from Django.
Related
I have a django project with custom user model. When the user registers, he also gives url of his company's website. I access and display it in the template using the USER. But it won't open as a separate link when I write it in an anchor tag as follows:
<li><b>Company Website</b><br>{{ detail.company_site }}</li>
Instead it takes me to this link
http://localhost:8000/detail/ahftech.com
Well, I figured it out myself. I simply added https:// as follows:
Before:
<li><b>Company Website</b><br>{{ detail.company_site }}</li
After:
<li><b>Company Website</b><br>{{ detail.company_site }}</li>
We have a continuing need to update an ads.txt file that lives at the root of a Django project. The current method to update this file is ftp it and a “service nginx restart” performed by a developer. We want to now do this with a flat page and template and simply have a “non-developer” cut and paste the contents of the ads.txt file into the Content: field via the Django administration app, save and all should be well. The issue is the line breaks do not render unless we add html <br> tags. This causes the ads.txt file to not pass validation tests since no html is allowed, only plain text. How can we accomplish this?
The template is simply
{{ flatpage.content }}
Trying
{{ flatpage.content|linebreaks }}
causes html tags to be inserted into the rendered page and fails the ads.txt test. We’ve tried various combinations such as
(r'^ads_txt/$', 'media.views.custom_header')
in urls.py and
def custom_header(self):
self.response.headers['Content-Type'] = 'text/plain'
in views.py to no avail.
Have you tried the striptags tag?
{{ flatpage.content|linebreaks|striptags }}
I'm working in a Flask app, and I'm trying to set it up to create dynamic webpages based on the data in the SQL database. For example, if we scrape data about a certain criminal, I want Flask to route my requests such that I can type:
myflaskapp.com/criminal/[criminal's name]/
and be taken to a page specifically for that criminal. This is the relevant portion of the views.py that I've already written:
#app.route('/criminal/<first_name>')
def criminal(first_name):
criminal = Individual_Criminal.query.filter_by(first_name=first_name).first()
return render_template('user.html',
criminal=criminal)
Now, when I call the Individual_Criminal.query.filter_by(first_name=first_name).first() in a Python shell, it returns as expected:
However, when I set up my Flask server, and do (what I believe to be) the exact same command query, it just gives me a blank page (with my navbar and stuff extended from the base html.)
The HTML for the page I'm trying to call is simple:
<!-- extend base layout -->
{% extends "base.html" %}
{% block content %}
<h1>{{ criminal.full_name }}</h1>
<hr>
{% endblock %}
As you can see, it should be returning the particular criminal's full name (in this case, Bryan Sanford). Instead, it returns this:
Instead of the requested criminal's full name, the way that the HTML specifies.
Where am I going wrong here? My thinking is that if I can do that exact query that's in my views.py file and have it return the correct value, it should work the same in my Flask app. However, clearly there are some wires crossed somewhere. Can any of you wonderful people help me untangle this?
edit: as discussed in one of the answers comments, when I change views.py to include print(criminal.first_name), it fails, throwing AttributeError: 'NoneType' object has no attribute 'first_name'. Even though the exact same line works exactly as expected in the actual database!
Your routing seems to be wrong?
This is not the same
myflaskapp.com/[criminal's name]/
as
#app.route('/criminal/<first_name>')
Try
myflaskapp.com/criminal/[criminal's name]/
Using frozen flask to make my website static, I have the following problem.
While all of my pages are being built (file//c:/correctpath/build/2014/page-title/index.html) the links to the pages are file:///c:/2014/page-title/.
Is there something I have missed?
EDIT:
In my template I have something like
{% for page in pages %}
{{ page.title }}
{% endfor %}
where .url() is a method on the page object:
return url_for('article', name=self.name, **kwargs)
url_for produces absolute paths (e. g. /2014/page-title) - when you open up your files in the browser it follows the rules regarding relative URL resolution and strips the extra file contents. If you just want to view your files as they will be seen on the server, Flask-Frozen has a run method that will let you preview your site after generating it.
Alternately, you can set FREEZER_RELATIVE_URLS to True to have Flask-Frozen generate links with index.html in them explicitly.
Rather than setting FREEZER_RELATIVE_URLS = True, with resulting URLs ending on index.html, you can also set FREEZER_BASE_URL to <http://your.website/subdir>.
I am running a Django website and I want to be able to upload a file through my admin panel and then have visitors to the main site be able to download it. I am running my site using Django-nonrel, Django FileTransfers and Google App Engine. I believe the upload functionality is working correctly as I am able to see the file in my App Engine Blob Storage. What I can't seem to figure out is how to present a download link to the specified file on the public website. I have pasted the relevant classes below:
I have an app called Calendar, that has the following model:
class CalendarEvent (models.Model):
start = models.DateTimeField(auto_now=False, auto_now_add=False)
end = models.DateTimeField(auto_now=False, auto_now_add=False)
title = models.CharField(max_length=500)
description = models.TextField()
file = models.FileField(upload_to='uploads/%Y/%m/%d/%H/%M/%S/')
Here is the view:
def calendar(request):
events = CalendarEvent.objects.exclude(start__lt=datetime.datetime.now()).order_by('start')
return render_to_response('home/calendar.html',{'events': events},context_instance=RequestContext(request))
def download_handler(request, pk):
upload = get_object_or_404(CalendarEvent, pk=pk)
return serve_file(request, upload.file, save_as=True)
Here is my admin:
class calendarAdmin(admin.ModelAdmin):
list_display = ('title','start','end')
admin.site.register(CalendarEvent, calendarAdmin)
Finally, here is the relevant part of my template:
{% for e in events %}
{% url Calendar.views.download_handler pk=e.pk as fallback_url %}
Download
{% endfor %}
{% firstof e.file|public_download_url fallback_url %} is just returning blank, i'm not sure where I am going wrong.
The GAE blob store does not support public download according to the documentation here, so if you use the default backend for public download urls, it returns None. So my guess is that e.file|public_download_url always return None. You could verify that.
Then I think your template is wrong. You're trying to access e.views.download_handler where it should be Calendar.views.download_handler if your app is named Calendar.
I think the sample on the django-filetransfers page is error prone because the variable used in the template loop has the same name as the sample app: "upload".
If this doesn't fix it, could you post your urls.py from Calendar app. It could be that the template's url method is not able to resolve the url for Calendar.views.download_handler if there is no mapping in urlpatterns.
You should have something like
urlpatterns = patterns('Calendar.views',
...
(r'^download/(?P<pk>.+)$', 'download_handler'),
...
)
in this file.
I don't see anything special, eg
Download File
should work, or just use e.file.url directly?
I haven't deployed on Google App Engine myself, but this appears to be what django-filetransfers was designed for:
http://www.allbuttonspressed.com/projects/django-filetransfers#handling-downloads
edit: I believe I've answered this in the other question you posted, then: Trouble downlaoding file using Django FileTransfers
I think easiest way is to write a view since this file blob cannot be retrieved directly to write a function which is such:
def file_transfer(req, calendar_event_id):
try:
ce = CalendarEvent.objects.get(calendar_event_id)
except CalendarEvent.DoesNotExist:
raise Http404()
file = ce.file (Write Google appengine specfic routine to pull file)
return HttpResponse(file, media_type='file content type')
Hook it up on urls.py