I'm currently working on a question bank website using Django 1.87 that allow users o login and view saved past questions. so far i have been able to display links to the past questions in the database base on user selection. the past questions are uploaded as docs or PDF format and stored in the media directory.
I want logged in users to be able to open and read the content of the past question before deciding whether to print or download it. so far i have been able to display a list of links to the documents and when i click on a link it downloads the document to my computer. what i really want to achieve is for users to be able to click on a link and open the document from within the browser before clicking a download buttenter code hereon or print.
here are my codes:
models.py
class QuestionBank(models.Model):
date = models.DateField(_("Date"),default=date.today)
class_level = models.ForeignKey(ClassLevel)
course_name = models.CharField(max_length=350)
course_code = models.CharField(max_length=20)
question_papers = models.FileField(upload_to = 'Question_Papers/ %y/%m/%d')
views.py
def Questions(request, sel_course):
context = RequestContext(request)
SelCourse = sel_course.replace('_',' ')
context_dict = {'SelCourse':SelCourse}
try:
Quest_For_course = QuestionBank.objects.filter(course_code = SelCourse)
context_dict['Quest_For_course'] = Quest_For_course
except course_code.DoesNotExist:
pass
return render_to_response('Qbank/QuestionsPage.html', context_dict, context)
in my Template i have this
QuestionsPage.html
<title> Question Papers </title>
<body>
<h2> LIST OF QUESTION PAPERS FOR {{selCourse}} </h2>
<h3> Select question to view, download or print it</h3>
{% if Quest_For_course %}
<ul>{% for ques in Quest_For_course %}
<li><a href="{{ques.question_papers.url}}">
{{ques.question_papers}} </a></li>
{%endfor%}
</ul>
{%else%}
<strong> THERE ARE NO AVAILABLE QUESTION FOR THIS CLASS AT THE MOMENT </strong>
{%endif%}
</body>
how do i make past question documents view-able? on a form that has download and print button. thanks
Related
So I want to make a blog post with HTML formatting from the admin page directly. For example from the models.py, you see the description is a TextField. When I go to the admin page to make a blog post, I want to be able to add HTML tags to my blog. So the text field will have HTML content. While I call the blog post onto the HTML template I want it to read the description as a HTML file and not just a text field.
models.py
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
date = models.DateField()
Blog.description at admin page
<HTML>
<body>
<p>Welcome to my first blog post!!</p>
</body>
</html>
blog.html
<h1>{{ blog.title }}</h1>
<hr>
<p>{{ blog.description }}</p>
Any help is appreciated. Thanks!
You can render it with the |safe template filter [Django-doc]. This will disable escaping HTML fragments, and it will thus no longer convert < to < for example:
<h1>{{ blog.title|safe }}</h1>
<hr>
<p>{{ blog.description|safe }}</p>
You however might want to take a look at the django-ckeditor package [GitHub] which offers a dedicated field, widget, etc. to enable editing the text with respect to rendering.
I am not sure if this question has been answered before, I tried to find other answers, but was unsuccessful, it may be that I am not put the right searches.
I am trying to complete the CS50 Web Finance project, and I'm running into a wall with the very beginning of the portfolio page. More specifically, I'm having trouble extracting data from my finance.db on my python page and then displaying it on my portfolio.html page. I think that I have successfully extracted the username from my finance.db, as shown in the code below.
#app.route("/")
#login_required
def index():
"""Show portfolio of stocks"""
# look up the current user
user = db.execute("SELECT username FROM users WHERE id = :id", id=session["user_id"])
return render_template("portfolio.html")
But, no matter what I do in my portfolio.html I cannot get it so say "Hello [username]" is just keeps saying "Hello undefined"
{% extends "layout.html" %}
{% block title %}
Home
{% endblock %}
{% block main %}
<p>Hello {{ [username] }}</p>
{% endblock %}
I'm sure this is something that most people are able to get, but I'm still kind of new and I just don't understand. I've tried to look up resources, but the only thing I've found is other people's code, and I don't want to copy and paste, I want to learn how to do it properly, so any help would be greatly appreciated. Thank you so much in advance.
In flask, you just need to 'pass' the username info to your portfolio.html page via render_template.
So, like:
return render_template("portfolio.html", username=user)
Then display this in the template with:
<p>Hello {{username}}</p>
I have a webapp where a user can upload a pdf file. I want the user to be able to click a button to be able to see the file in the browser.
I'm not sure how to link the pdfs as when they are uploaded they get given a random name by django in my static root. eg: hello_0akcjs.pdf
My View
def pdf_view(request, pk):
Menufile = Menu.objects.get(pk=pk).menuFile
with open('Menufile', 'r') as pdf:
response = HttpResponse(pdf.read(), content_type='application/pdf')
response['Content-Disposition'] = 'inline;filename=some_file.pdf'
return response
URL
path('<int:pk>/', pdf_view, name='pdf_view'),
Model
class Menu(models.Model):
name = models.CharField(max_length=50)
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
menuFile = models.FileField(upload_to='menus')
Template
{% for menu in menus %}
View Menu {{ menu.name }}
{% endfor %}
As it stands, everything works, except i just dont know how to get the pdf to be rendered at the URL for that model instances PK.
I was making it far too complicated. All i needed to do was reference the menuFile URL in the template.
Example:
View Menu
To display a pdf you have to use an embed tag,
<embed src={% url 'pdf_view' menu.pk %} width="500" height="375" type="application/pdf">
I have a Django project with an HTML file that lists all of the CSV files that have been uploaded to my Postgresql database and when you click on the CSV of interest a new page is rendered with the CSV model's basic information (name/time submitted).
This is the First Page:
{% for csv in Data_List %}
<button class="btn btn-primary" style = "font-size:1.2em;" >{{csv.name}}</button>
<br><br>
{% endfor %}
This is the second page:
<p>{{request.user.username}}'s Note
<h6>{{worklog.name}}
<br>
{{worklog.date}}
<br>
{{worklog.notes|safe}}
<br>
{{worklog.mycsv|safe}}
</h6>
</p>
However, my goal is that when you click the button a python VIEW will be passed (or just retrieve) the chosen posts primary key (or other information). I want to do this so the view can ask the database for the actual CSV and do some work.
How can I get a view.py to request a selected posts information such as primary key?
Thanks and Happy Coding
#The url
url(r'^anote/(?P<pk>\d+)$', views.A_Note, name = 'anote'),
#The view
def A_Note(request, pk):
#the rest of code here
return render(request, "some.html", {"thing":thing, "pk":pk, "etc":etc})
I learned that sharp brackets <> in a url passes the value through to the view where it can then be accessed as an argument when defining the view. From there it can easily be used in the code.
Thanks!
I am using WMD in a google app situation whereby the site administrator can update the pages of the site and the users see the information.
The preview function is working fine and I can see the text the way I want it to appear, but when I am in the users section, the markdown is being returned without the formatting - how can i fix this?
This is the code i am using
{% block content-left %}
{% if is_admin %}
<div id="content-bodyleft" class="wmd-preview"></div>
<form action="/admin/content/" method="post">
<textarea id="markdown" name="markdown" style="width: 400px; height: 200px;" >{{ page_content.html }}</textarea>
<input name="page" type="hidden" value="{{ request.path }}" />
<input type="submit" name="Save" />
</form>
<div class="wmd-output"></div>
<script type="text/javascript">
// to set WMD's options programatically, define a "wmd_options"
// object with whatever settings
// you want to override. Here are the defaults:
wmd_options = {
// format sent to the server. Use "Markdown" to return the markdown source.
output: "Markdown",
// line wrapping length for lists, blockquotes, etc.
lineLength: 40,
// toolbar buttons. Undo and redo get appended automatically.
buttons: "bold italic | link blockquote code image | ol ul heading hr",
// option to automatically add WMD to the first textarea found.
// See apiExample.html for usage.
autostart: true
};
</script>
<div class="wmd-output"></div>
<script type="text/javascript" src="/static/wmd/wmd.js"></script>
{% else %}
{{ page_content.html|markdown }}
{% endif %}
The reason this is happening is because the Django Form is only seeing the value of the <textarea> tag that represents WMD editor. That value is the actual markdown, not the rendered HTML that you see in the preview.
There are several ways to fix this, on either the client or the server...
When the form is saved, convert the markdown to HTML on the server using a python markdown module, like this one
When the form is submitted on the client, have javascript replace the value of the WMD <textarea> tag to the actual HTML
Option #1 is probably the easiest. Here's some sample code...
import markdown
class MyModel(models.Model):
text = models.TextField()
def save(self, force_insert=False, force_update=False):
if self.text:
self.text = markdown.markdown(self.text)
super(MyModel, self).save(force_insert, force_update)
This doesn't appear to have anything to do with WMD.js, which is an editor and has nothing to do with displaying the content.
You don't post your models, but it looks like you are entering content into the "markdown" field, but displaying a different field, "html". I presume you have something in your models - maybe on save - that populates that html field with the converted markup?
Also are you sure you're seeing raw markdown, or are you seeing raw HTML? I would assume you would need to unescape the html output:
{{ page_content.html|safe }}
This is my models.py file
# models.py
from google.appengine.ext import db
class GoogleToken(db.Model):
session_token = db.StringProperty()
scope_url = db.StringProperty()
added_on = db.DateTimeProperty(auto_now_add=True)
class PageContent(db.Model):
html = db.TextProperty()
page = db.StringProperty()
class PageMedia(db.Model):
name = db.StringProperty()
type = db.StringProperty()
content = db.BlobProperty(default=None)
class Announcement(db.Model):
title = db.StringProperty()
content = db.TextProperty()
added_on = db.DateTimeProperty(auto_now_add=True)
and this is from views.py
def content(request):
html = request.POST.get('markdown', None)
page = request.POST.get('page', None)
logging.debug(html)
logging.debug('Page: %s' % page)
query = PageContent.all().filter('page =', page)
page_content = query.get()
if page_content == None:
page_content = PageContent(html=html,page=page)
else:
page_content.html = html
To help you understand what is happening, for example I am typing
Title
----
*Subtitle*
Text text text
and seeing
Title
Subtitle
Text text text
in preview, but on output i am seeing
Title----*Subtitle*Text text text
Thanks, I do appreciate your help with this.