Integrating a frontend js framework (Vue) for django - django

I am a Laravel developer and used Vue as my frontend framework in the past.
However, I got interested in learning Python, specially its web framework equivalent - Django. Compared to Laravel, Django is pretty much way better in all aspects - it's fast, it's one of those 'all-in-one' type of framework, plus it's PYTHON. A 15-minute task in Laravel can be accomplished in Django for 5 minutes.
One thing that's just bugging me is how to integrate Vue on its templates. I tried the normal CDN method but it doesn't actually work. I figured maybe because django's syntax -{{ sample variable here }} and Vue's are the same. I tried writing delimiters like delimiters: ['[[', ']]'], but it just made it more complex and still will not work.
I tried doing the webpack method which install a separate vue project within the django project, then used several (like a lot of third-party plugins) to somewhat connect the vue project, to the django project. It is so tedious on its process and it seems like it's not the why it should be. I kinda miss it on Laravel where you could just create an app.blade.php main template, import app.js on it, then just take it from there.
Is there a way to just integrate Vue on django's templates quickly like you can on Laravel?

We use Vue with Django via cdn, and it is pretty easy to set up as you can do everything in the template file.
You have to be sure to import Vue via script tag somewhere on the page and then either define your own delimiters (as you've done) or use the {% verbatim %} {% endverbatim %} tags around any variables you do not want django to try and evaluate. You can either write your Vue function in a script tag on the page or import an external file via script tag the way you would import any other js file into a django template. If you posted your template code, I might be able to provide more guidance.

Related

Django - Best way to organize/serve mostly static website?

My friend with very little coding experience began making a business site and passed it on to me. Currently, it is mostly static html and css files but I want to take what he has and build on it using Django because I will be adding features like user login/auth and checkout. I was wondering what the best thing to do with all these html and css files are and how I might go about fitting it to Django framework.
All of the content on these pages will be static but I could imagine in the future once I add a login, the header might be different to show whether or not a user is logged in. Would I need to make separate apps for each page, include them all in one app, or just put them all in the static folder?
Would I need to make separate apps for each page
Assuming you are referring to django apps. Then No, you do not need to create a separate application for each page. django apps are a way to organize individual pieces of your projects.
To gain the most out of django, I would suggest looking into the Django Template Engine to improve the html (blocks, include and extend etc) and make it more readable and future proof ( urls, media, forms)
just put them all in the static folder?
I'm not sure you'd be able to get away with it being in the static folder, Static files in django are used for CSS and Media files such as images, videos etc. To render a template in django you need use render() or TemplateView
I hope this helps clear up some of your doubts.
Django is a Model-View-Template (MVT) framework where you create templates (HTML files) and use Jinja syntax there to display the data passed from Django views. You don't need to create apps for each page, instead, you can define functions in an app's views.py file and then reference that view from the corresponding path (URL) from the urls.py file.
You can create a main HTML template that will be extended by each sub-page. And applying your logic to your main template's header (i.e. if/else) in the main template will affect your all pages.
My recommendation is that you should first study the Django docs carefully and understand at least it's basics before starting the migration of the HTML site to Django. Django has one of the best documentation available for software on the Internet and you should be grasping the basics very quickly if you have a little programming background.

How can I apply changes when clicking on an html checkbox in a django project?

In my current django project I have the following model:
Python 3.7.1 / django 3.0
class SampleClass(models.Model):
active = models.BooleanField(default=False)
And the following template code with 'sample' as an instance of the SampleClass above (only small snippet):
HTML / django template language
<form action='#' method='post'>
<input type='checkbox' name='is_active_checkbox' {% if sample.active %}checked{% endif %}>
</form>
Now, when the state of the checkbox is changed, I would like to immediately apply the change to the django database, without reloading the page (if possible). Is there any way to do that?
I would recommend you to start with a basic AngularJS, there are several functions that you can apply quickly, this option allows you to just add a CDN and keep working the frontend from Django.
If you want to do something more robust, you can apply Angular 8+. Here you should use Angular as a web server, and Django as REST Apis.
Here are some basic examples, where you can adapt it to your needs and play around with the theme. I've been working with Django for more than 6 years, but I started to integrate it with Angular less than a year ago (you can choose React, Vue, or whatever suits you best, but Angular was a comfortable decision for me)
I leave you here my Github with several examples of Django with all its code, there is also 1 pair with React.
Github/Django

Editing a previously generated HTML file with Django

I am very new to web development and the following is my use-case :
I have a large number of Bokeh charts, each in a separate HTML file.
In simple terms, I would like to have a home page, where I can provide
links to each one of these charts. However, During runtime, I would
like to edit these separate HTML files, so as to provide a link to go
back to the home page or to other pages. I would not like to modify
the HTML files permanently, so I can make use of them outside of the
web page as well for simple visualization on my system.
What is the best way to do this ? Are there technologies outside Django, I should be looking at to do something like this ?
If most of the content is static, maybe have a look at Jekyll.
The include functionality would let you create one file with the 'link back to the homepage' or in fact further content which you want to avoid repeating (such as navbars, headers, footers).
Bootstrap 4 is your freind for making the site look shiney.
As you're building the site you can run the development server with jekyll serve which allows you to connect to a development server from your browser, and preview changes as you're making them. This would be accessible somewhere like http://localhost:4000/
When you're ready to publish, you can use the jekyll build command, which outputs all of the static HTML files to the _site directory. Notice that at this point, the step of 'putting the homepage link in every page' is handled automatically by Jekyll and you end up with a directory you can upload directly to any hosting platform. The original HTML files/Boken Charts can therefor remain in their original form for use elsewhere.
This method is probably much more effiient than using Django for your use-case, which seems to require serving lots of static content whch already exists. With Django in production you'd need an application server, as well as a webserver and possibly a database which means more things to go wrong.
For bonus points, once you've got the hosting setup, stick the whole thing behind CloudFlare to reduce your hosting costs, and improve access speeds for visitors around the world!
Good luck.
EDIT: response to comment:*
Do you mean that I should abandon django altogether ?
If the purpose is just to serve your exising HTML files to the public, without any requirement for authentication, editing of content by users through the frontend, or more advanced back-end functions, then yes Django is probably overkill for this task.
How is Jekyll different from Django ?
Django is a Python Web Framework, which allows you to build an interactive site on which users or staff can login, post articles, comment, etc. One of its key features is the ability to define database relationships trough 'Models' and then have all the admin-side forms generated automatically in the background. This means, with minimal work, you can instantly have the 'admin portal' side of the site live, which works great for use-cases like large blogs or news sites. You would then build the frontend, which can also be interactive. To launch this into production is a separate task which involves configuring multiple server components.
Jeykll on the other hand is much simpler, and basically gives you a way to create some template HTML files (avoiding the need to repeat code for stuff like navigation bars) and then with the jekyll build command outputs a _site directory which can be uploaded straight to a basic webserver. This is the crucial part, as you then only need a webserver which can serve static content, rather than requiring python, a database, application server like UWSGI, etc
Let's look at this example from the Jeyll Docs with your usecase in mind.
You could define a YML file with a list of all your charts:
docs_list_title: All Charts here.
docs:
- title: A Lovely Bokeh Chart.
url: bokeh_chart_1.html
- title: This Bokeh Chart is even Better
url: bokeh_chart_2.html
You mentioned previously that you already have the HTML files, so really what you've done here is made a list of those, which can be interpreted by the frontend.
The HTML template portion would look something like this:
<h2>{{ site.data.samplelist.docs_list_title }}</h2>
<ul>
{% for item in site.data.samplelist.docs %}
<li>{{ item.title }}</li>
{% endfor %}
</ul>
This would result in a list of links to all of your Charts, with the link text as the title.
Obviously you could then go further and add further info to the YML file, like beneath each url put publisher: someone which could then be accessed in the template's for loop as {{item.publisher}}
Can such tools like Jekyll, Django and Bootstrap be used together ?
Bootstrap can be used with Django or Jekyll, as it is a CSS library which controls how HTML is rendered in the user's browser. Check the documentation for more examples of its capability.
A good starting point may be to download a theme from somewhere like Start Bootstrap. Once you have that as a ZIP file, you can put it in your Jeykll project and attempt to have it render through the dev server with jekyll serve. You can then remove nav bar or header code to separate include files (see my earlier link to the Jeykll docs) and before you know it you'll be seeing progress.
The best way to learn is to just go ahead and try this!

Using Polymer Inside Django

I have a Django project already running with its UI created using Bootstrap and some custom CSS, JS.
Currently going through the Polymer Starter project, I want to do a UI makeover for my Django project using Polymer. Being a beginner with Polymer, my first question is, Is it feasible?
If yes, I would like to know from where should I start? I am not getting should I just remove all bootstrap and CSS already used and start replacing my old elements with newer Polymer elements? I have tried including Polymer elements in Django templates, but it doesn't seem to work this way.
I am just not getting the steps to follow for such a UI makeover.
Any piece of help will be greatly appreciated.
Refer to this https://groups.google.com/forum/?fromgroups=#!searchin/polymer-dev/django/polymer-dev/N2R8qknalOI/58ZhC1gWFh4J.
You should be able to wrap Polymer elements in Django templates. They are just static files. Just make sure you are using {% verbatim %} tags to wrap around your polymer elements.
However, if you are going for a complete UI makeover, use AJAX calls to the REST services running in the background on Django. Or if you do not want to use django-rest-framework or tastypie or something new, you can slightly modify your existing view functions to serve JSON that packs all the data you need for a dynamic page.

Adding React inside a Django project

I am a Django developer just getting started with adding React to one page of my app, and really enjoying it so far. (It's a normal Django app with a home page, an about page, etc, but also a "chart" page with an interactive chart, and I want to build the interactive part in React.)
The problem is that I've started with the downloadable React starter kit and I'm not sure how to do things the 'right' way, and it's complicated by using Django to serve my project (all the tutorials seem to assume you're using node, which I'm not).
Right now I just have this in my Django template:
<div id="myapp"></div>
<script src="/static/js/vendor/react.js"></script>
<script src="/static/js/vendor/JSXTransform.js"></script>
<script src="/static/js/myapp.js"></script>
And myapp.js has all the React code. I'm aware this isn't really the grown-up modern JS way of doing things.
Now I want to use React Bootstrap, but it seems that the only sensible way to do that is with npm. So it's time to make the switch, but I'm not completely sure how.
I have run npm install react and npm install react-bootstrap from inside my static/js directory in Django. This has created a node_modules folder with various files inside.
So three questions from a confused newbie:
Where should I put my React code to work with these npm modules (should I use var React = require('react')?
Do I need to compile this code somehow (using webpack?)
How do I then integrate this with Django? Should I compile it all to myapp.js and just include that in my HTML template?
I'm also doing the same thing right now - moving away from embedded HTML script tags into require land. Here is the tutorial I am following, and here is my file system so far. I am doing it in Node but it shouldn't be that different for a Django project as the React frontend code is decoupled from any backend other than API URL's.
Your node_modules folder contains react-bootstrap. In your myapp.js, use the require('react-bootstrap') to load up the library which is contained in your node_modules folder.
Where should I put my React code to work with these npm modules (should I use var React = require('react')?
You can put the code anywhere. If your file system looks like this:
project/
react/
myapp.js
node_modules/
react source code
react bootstrap stuff
Then you can just do var React = require('react'); in myapp.js.
Do I need to compile this code somehow (using webpack?)
Yes, I would consult the webpack tutorial I linked earlier, it should explain how to compile all your React code into a single bundle.js. Here is also another good tutorial. This bundle.js file contains all the source code of your requires. So if your myapp.js looks something like
var React = require('react');
var ReactBootstrap = require('react-bootstrap');
then the bundle.js now contains all of the React and react-bootstrap javascript code, along with the myapp.js source code.
How do I then integrate this with Django? Should I compile it all to myapp.js and just include that in my HTML template?
I've only done work on Nodejs, but my React code so far hasn't touched any Node code, and I don't think it will touch any Django code (again I've never done Django so I might be wrong). All you need to do is compile with webpack, which spits out a bundle.js. You put that bundle.js in your HTML and it'll load up myapp.js.
ReactJS code is still JS code. Even though you do require/import/other module based syntax when coding, in browser you will still load the JS code by a script tag.
The problem is how to let the script generated by webpack(bundle.js) to work with other 'VanillaJS' script. For example, if you only write an individual component using React, like a small table. And its data(props/state) will depend on another element/event written in VanillaJS, e.g, a click listener on a button render by django template. Then the question is, how they communicate with each other.
So far, the solution I know is:
when you write React Code, instead of calling ReactDOM.render explicitly with preset props/state, you can store that in a global function, the arguments could be the props. You load this script first, then the other script can use this global function to trigger the React render Component.
I'm using Django Rest Framework to build an API and then connect to that API from React (using simple Create react app), this way the front end and back end are separated and the application is very scalable. The second way to do this, is call create react app then run build and point your django settings to that react build, this way the front end is not separated from the backend. I hope this helped, good luck.