Render html from a db field in Django - python

In my django project I have a model with a field that contain html code as text:
html_test = models.TextField()
for example in this field could be:
<html>
<header><title>This is title</title></header>
<body>
Hello world
</body>
</html>
I want to retrive this code and render dynamically showing the corresponding html page without create a file or save it on disk.
How can i render an html code in memory for display page and then destroy it?

I'm still not sure what your actual question is. You retrieve the model from the db and return the data to the user, just like anything else. For example, a view might look like this:
def my_view(request, pk):
obj = MyModel.objects.get(pk=pk)
return HttpResponse(obj.html_test)

Using jinja2 as the templating engine,
class YourClassName(generic.TemplateView):
template_name = 'your_template.jinja'
def get_context_data(self, **kwargs):
kwargs['html_data'] = MyModel.objects.get(pk=pk).html_test
return super(YourClassName, self).get_context_data(**kwargs)
In your your_template.jinja
<html>
<header><title>This is title</title></header>
<body>
{{html_data}}
</body>

Related

I want to use the if statement based on the existence of a web page

So basically i have a complicated scenario. I am current using Django to build a website and i have current made two apps. Both apps have almost identical fields. The field I would want to focus on though is the Information field(which they both have and which i have auto generated with the help of the Wikipedia model)
So the case here is that I want to create an if and else statement in the html in such a way that if the page i am hyperlinking to exists it would go to the link dealing with DetailView but if it doesnt exist I would redirected to the Create View
I should also note that the two apps have their names linked with the help of the foreign key but when i try to open information links using the same name , they gave me different pks
I dont feel like i explained my problem well enough but I hope someone can understand what i mean
UPDATE
ok I create the get function using
def get(self, request, *args, **kwargs):
try:
self.object = self.get_object()
except Http404:
return redirect('/create/')
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
but i dont know how to use the CreateView fuction i created instead of the link i put
This is the Detail View Html
{%extends "home.html"%}
{%block head_title%} {{block.super}}{%endblock head_title%}
{% block content%}
<!-- verify authentication -->
{% if request.user.is_authenticated%}
<h3>{{object.title}}</h3><br/>
{% endif %}
<ul type="disc">
<div class="container">
<li><b>Artist: </b>{{object.Summary}}</li>
<li><b>Genre: </b>{{object.Genre}}</li>
<li><b>Bio: </b><br>{{object.Bio}}</li>
EDIT
</div>
</ul>
{%endif%}
{% endblock %}
This is my model
from django.db import models
from django.conf import settings
from Blog.models import MainPage
from django.urls.base import reverse
from Blog.Retrieve import retriever
from django.db.models.signals import pre_save,post_save
import InfoPedia
class InfoPedia(models.Model):
user =models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
Name =models.ForeignKey(MainPage,on_delete=models.CASCADE)
Location =models.CharField(max_length= 50,null=True,blank=True)
Information =models.TextField(null=True,blank=True)
TrackListing=models.TextField(null=True,blank=True)
Published=models.BooleanField(default=True)
Timestamp=models.DateTimeField(auto_now=True)
Updated=models.DateTimeField(auto_now=True)
def get_absolute_url(self):
# return f"/Blog/{self.slug}"
return reverse('InfoPedia:DetailView', kwargs={"pk":self.pk})
class Meta:
ordering=["-Updated","-Timestamp"] #orranges in order of updated
def get_tracklist(self):
return self.TrackListing.split(",")
def Information_create_pre_save( instance, sender, **kwargs):
instance.Information=retriever(instance.Name)
def rl_post_save_reciever(sender, instance,created,*args,**kwargs):
print("saved")
print(instance.Timestamp)
pre_save.connect(Information_create_pre_save, sender=InfoPedia)
post_save.connect(rl_post_save_reciever, sender=InfoPedia)
An alternative - rather than checking the if/else in the HTML, just make all the links to the DetailView URL.
Then, in the get() handler for the DetailView, you perform a queryset lookup for the object. If no object is found, then instead of displaying the DetailView HTML, return to the user a 302 redirect (i.e. a temporary redirect) to the CreateView for that object. So all your if/else logic is in the view function or class, instead of HTML.

CSS and JS not loading on webpage

I'm following a course online but am stuck, I'm using webpy to create a little website on my localhost server. The CSS and JavaScriptwork perfectly on all pages but one, I'm not sure if it is to do with the regex in the url?
The CSS and Javascript is called on the Mainlayout html page and the page is called under the Navbar with $:page
I use the URL path: '/profile/(.*)/info', 'UserInfo', and '/profile/(.*)', 'UserProfile',
Then define the classes as:
class UserProfile:
def GET(self, user):
login = LoginModel.LoginModel()
user_info = login.get_profile(user)
post_model = Posts.Posts()
posts = post_model.get_user_posts(user)
return render.Profile(posts, user_info)
class UserInfo:
def GET(self, user):
login = LoginModel.LoginModel()
user_info = login.get_profile(user)
return render.Info(user_info)
The CSS and JS are called on the main layout using:
$def with (page)
$var css: static/css/bootstrap.min.css static/css/bootstrap-material-design.min.css static/css/ripples.min.css static/css/jquery-ui.css static/css/custom.css static/css/materialdesignicons.min.css
$var js: static/js/jquery-3.2.1.min.js static/js/bootstrap.min.js static/js/material.min.js static/js/ripples.min.js static/js/scripty.js static/js/ripples.min.js static/js/jquery-ui.min.js static/js/material.min.js
$if self.css:
$for style in self.css.split():
<link rel="stylesheet" type="text/css" href="$style"/>
$if self.js:
$for script in self.js.split()
<script src="$script"></script>
These are the errors I get in the console:
Any tips on where I should look to get this working? I'm not sure what information I need to share for you to have the full picture so please ask if anything else is needed.

Django returning static HTML in views.py?

So I have a standard Django project with a basic view that returns a simple HTML confirmation statement. Would it be plausible for me to define all of my HTML in the view itself as a really long string and return that using HttpResponse() I know it's a bit unorthodox, but this is an example of what I'm thinking about:
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response
def index(request):
html = """
<html>
<body>
This is my bare-bones html page.
</body>
</html>
"""
return HttpResponse(html)
My corresponding JS and stylesheets would be stored in the same directory as views. py in my app in this example. Just making sure: I'm not asking if this works, because I already know the answer is yes, I just want to know if there are any disadvantages/drawbacks to this method, and why don't more people do this?
You can use built-in template renderer to get works filters/templatetags/etc
Most people dont use this because it mixes Python with HTML and gets very messy and out of hand very quickly
To answer your question, this solution works alright, but it is not adopted by many programmers because it makes the whole code disorganized and not easy to understand.
Also, this system would not be good for large projects because the code would contain lots of html in the same file as the python. It is always nice and time saving to separate code into files based on performance.
A better solution
Save your html in a folder called templates in the current directory, in this case, the templates folder can contain an index.html file which would have
<html>
<body>
This is my bare-bones html page.
</body>
</html>
in the views create an index view for this template using the code below
def index(request):
return render(request, 'index.html')
if you would need to pass in some data to the html you can use context in the request as shown below:
def index(request):
context = {
"name":"some name"
}
return render(request, 'index.html', context=context)
access the data in html using the structure below:
<html>
<body>
The data passed to the page is {{name}}.
</body>
</html>
I hope this helps

How to save POST DATA in django?

Here is an example having:
form with three fields i.e
from django import forms
from models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ('title','body','thumbnail')
view
from django.shortcuts import render_to_response
from uploadfiles.models import Article
from django.http import HttpResponse, HttpResponseRedirect
from forms import ArticleForm
from django.core.context_processors import csrf
def create (request):
if request.POST:
form = ArticleForm(request.POST, request.FILES)
if form.is_valid():
return HttpResponseRedirect('/all')
else:
form = ArticleForm()
args= {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_article.html', args)
models
from django.db import models
from time import time
def get_upload_file_name(request):
return "uploaded_files/%s_%s" %(str(time()).replace('.','-'))
class Article(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
thumbnail = models.FileField(upload_to = get_upload_file_name)
def __unicode__(self):
return self.title
html page
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<form action="/create" method="post" enctype="multipart/form-data">{% csrf_token %}
{{form.as_ul}}
<input type="submit" name="submit" value="create"/>
</form>
</body>
</html>
MY QUESTIONS ARE:
1)What is Meta class, why we use this?
2)What this line means args.update(csrf(request))?
3)As in forms page redirects to /create .. as this can be any page! so how to save posted data now. as this returns the submitted data to html page.
My question can be so basic or simple but these are the things that are not clear to me and for that reason i am posting this here! and it can be duplicate so if you don't like it please don't mark negatively.:)
1)
Metaclass is a 'thing' that creates classes.
You define classes in order to create objects, right?
But we learned that Python classes are objects.
Well, metaclasses are what create these objects. They are the classes' classes, you can picture them this way:
MyClass = MetaClass()
MyObject = MyClass()
You've seen that type lets you do something like this:
MyClass = type('MyClass', (), {})
It's because the function type is in fact a metaclass. type is the metaclass Python uses to create all classes behind the scenes.
Now you wonder why the heck is it written in lowercase, and not Type?
Well, I guess it's a matter of consistency with str, the class that creates strings objects, and int the class that creates integer objects. type is just the class that creates class objects.
for more help see this MetaClasses
2)
Cross-site request forgery (CSRF)
A Cross-site request forgery hole is when a malicious site can cause a visitor's browser to make a request to your server that causes a change on the server. The server thinks that because the request comes with the user's cookies, the user wanted to submit that form.
Depending on which forms on your site are vulnerable, an attacker might be able to do the following to your victims:
Log the victim out of your site. (On some sites, "Log out" is a link
rather than a button!)
Post a comment on your site using the victim's login.
Transfer funds to another user's account.
To PREVENT this we use this update(csrf(request))
for more information see this ABOUT CSRF and this CSRF django
3)
/create is a action of your present controller if you see your controller page there you can see this create function in that function you'll get your POST data
1) Meta = class metadata. This is where you define the different metadata elements of the model
2) CSRF = this is the token that prevents cross-site attacks. It is a hidden field/attribute that is added to your request to make sure someone cannot hack your site
3) The submitted data goes to the view and there your can save your data. Or I misunderstood your question....

Python Pyramid: Load view based on database variable

I just started pyramid and have a problem with loading views. I want to load a view based on a variable fetched from the database like my PHP solution here: rewrite url with htaccess
I've build a script that can do this, but I'm quite sure this is not the right way to do it. I think when I use this in a real site it will get very complicated and messy. Could someone explain how to this properly or point me to an other solution?
My current script:
config.add_route('home', '/')
config.add_route('admin_home', '/admin')
config.add_route('admin_pages', '/admin/pages')
config.add_static_view(name='static', path='website:static')
config.add_route('view_loader', '/*url')
views.py
class ViewLoader(object):
def __init__(self, request):
self.request = request
#view_config(route_name="view_loader", renderer="templates/view_loader.pt")
def view_loader(self):
request = self.request
url = "/%s" % request.matchdict["url"]
page = DBSession.query(Pages).filter_by(url=url).one()
return dict(title=page.title, include=page.template)
view_loader.pt
<!DOCTYPE html>
<html>
<body>
<metal:main use-macro="load: ${include}"></metal:main>
</body>
</html>
Idea of the system:
Admins can create pages in a cms with random url's and have to select a template. The system has to generate these pages.
url = /random/random -> look for template in db -> render template_1
url = /random2/random2 -> look for template in db -> render template_2
So I want to render the template after the class/method is being called to determine what template has to be rendered
I found a more logical approach for my problem with the help of this question Map different URLs to same view. Actually the solution is quite simple I just didn't know it is possible to declare a renderer in add_view()
main.py
pages = DBSession.query(Pages)
for page in pages:
config.add_route(str(page.name), page.url)
if page.template.decode('utf-8') == "home_view":
config.add_view(home_view, route_name=str(page.name), renderer='templates/home.pt')
elif page.template.decode('utf-8') == "detail_view":
config.add_view(home_view, route_name=str(page.name), renderer='templates/detail.pt')
views.py
def home_view(self, request):
return dict(.....)

Categories

Resources