I haven't been able to locate anything saying one way or the other, but does anyone know if you can have function based views in django and have react as your frontend? No use of templates.
If so, would it look like this?
# fad index route
def fad_index(request):
context = {'fads': Fad.objects.all()}
return render(request, 'fad/fad_index.html', context)
But instead of fad_index.html, would it just be the route that you want it to take in react?
When you use Django views, whether class or function based, you are required to render html responses, so there is no point on using React this way since the front-end functionality is already embedded in the html you are rendering.
React is thought for creating front-end applications that run independently from the back-end application. For that, the back-end application must provide specific url points for fetching or posting data from and to the front-end. These url points are known as end-points, and this back-end architecture is known as API, and come in two main flavors, SOAP and REST, and differ, basically, in the format of the data that comes from and goes to the front-end. SOAP APIs use xml, and REST APIs use json.
If you have a REST API back-end, you can use ajax in a React front-end to fetch and post data from and to the back-end's end-points.
For making a REST API back-end using Django, you need to complement it with another library called Django Rest Framework, that allows Django views to render json packages instead of html, so your React front-end can use these end-points.
React is simply a component composition library. You can use it to render single components on a web page or as the rendering layer of a more complex Single Page Application (SPA)
The general best practice when creating single page applications is to send the data over in a JSON format using a REST API. JSON because it can be parsed in almost any language and REST because the server should not care what the client is specifically doing.
There is a module called django rest framework that allows you to return raw data from REST style endpoints in a JSON format.
Related
I'm building an app in which I need to communicate data from and to ReactJS and Python. It needs to go both ways - but I'm more concerned about the React part right now. At first I considered JSON, but couldn't find any resources/ libraries to update JSON files, and people said I should stay away from that. Other than literally creating a text file with data in it, what are my options? The application has to do with getting stock data from a python API, doing calculations on it, and sending the data to ReactJS to render on a webpage. I also need ReactJS to send account data back to Python where we do our MySQL. Any suggestions?
Since the ReactJS app is a front-end application, your only real choice to ensure security is exposing an API on the python app which the ReactJS app talks to (via Websockets for example since you're mentioning a bidirectional communication). Maybe take a look at something like Flask with the flask-socketio package.
Does Django render websites and serve them from a views folder similar to how the express framework works in JavaScript? Or does it render pages on the client side similar to an applicatipn running express in the back-end and some fron end framework such as Vue.js in the front-end
Django can do either, but it is designed to render on the server side in its default configuration, not the client side.
To use server side rendering, use Django as intended and according to the many tutorials out there.
To use client side rendering with something like React or Vue, use the Django Rest Framework.
If you are talking about the template language, it happens on the backend. This is true of every framework and every language. In the templates, the placeholders are replaced, they produce a valid html/javascript page, and that's what is returned to the browser (or, to whatever accessed that url). Essentially, it is a shortcut for creating an html file by concatenating strings.
A suggestion: don't use the template language, in any backend framework. Just use django to create rest services that return the data, and use a front-end framework like Vue/angular/react to create the actual front end part.
It's now 2022 and you should definitely check out https://www.reactivated.io/.
It effectively is plain old Django with server-rendered React.
I have a django template that calls a python methods but I can't seem to find a way for the python method to retrieve information from the template such as user input. Could anybody tell me how to do this?
I think you're under a misconception (A reasonably common one) that because you can use django variables in the html template, the template can "send" information back to django/the database.
Instead, try to get into the habit of thinking in terms of request/response. The user requests a web page, the django server builds up the response using content from the database and an html template (via the template language) and serves it to the user. If the response page has a form in it, that's not the "template" sending information back to the Django server, that's the response web page providing the user will tools to make ANOTHER request (this time a POST request).
The template is merely a generic container that you fill up with your dynamic content to build up the entire HTTP response.
I currently build a web application using flask, sqlalchemy and jinja2.
To get a proper web interface, I build my views as follows:
#app.route('/mydata/', methods=['GET'])
#login_required
def mydata_list():
# build data here...
return render_template('mydata/index.html', data=data))
Now, if I need to build a REST API, I am supposed to terminate with
return jsonify(data)
So, how to handle this to avoid code duplication? Is it a good practice to add a ?api=True to my url, test it in my view, then return appropriate answer?
There is really no right or wrong way to do this, more so with Flask, which is a framework that imposes so few rules on the developer.
If you want my opinion, I think using the same set of view functions for web site and API leads to code that is harder to maintain, because there are a few significant differences between the two, for example:
Authentication: this is typically done in very different ways for web vs. API.
Content: for the API you just return data, but for a web page the view function may need to do more work and obtain extra data that is only needed for rendering the template.
Request methods: APIs use more HTTP request methods than web apps. For example, to delete a resource through an API the client normally sends a DELETE request. A web application running on a web browser needs to do everything with GET and POST requests. Also, the POST request method has different usages in APIs vs. web apps.
My recommendation is that you make your view functions for both APIs and web apps very thin and put the business logic of your application in common classes that both sets of view functions can invoke.
If you want to use the same endpoint for serving a template as well as JSON data, you can test whether this is an AJAX request with request.is_xhr. For example:
#app.route('/numbers/')
def numbers():
data = [1, 2, 3]
if request.is_xhr:
return jsonify(data=data)
return render_template('numbers.html', data=data)
What is a good/simple way to create, say a five page wizard, in Python, where the web server component composes the wizard page content mostly dynamically by fetching the data via calls to a XML-RPC back-end. I have experienced a bit with the XML-RPC Python module, but I don't know which Python module would be providing the web server, how to create the static content for the wizard and I don't know how to extend the web server component to make the XML-RPC calls from the web server to the XML-RPC back-end to be able to create the dynamic content.
If we break down to the components you'll need, we get:
HTTP server to receive the request from the clients browser.
A URL router to look at the URL sent from client browser and call your function/method to handle that URL.
An XML-RPC client library to fetch the data for that URL.
A template processor to render the fetched data into HTML.
A way to send the rendered HTML as a response back to the client browser.
These components are handled by almost all, if not all, Python web frameworks. The XML-RPC client might be missing, but you can just use the standard Python module you already know.
Django and Pylons are well documented and can easily handle this kind of project, but they will also have a lot of stuff you won't need. If you want very easy and absolute minimum take a look at using juno, which was just released recently and is getting some buzz.
These frameworks will handle #1 and provide a way for you to specify #2, so then you need to write your function/method that handles the incoming request (in Django this is called a 'view').
All you would do is fetch your data via XML-RPC, populate a dictionary with that data (in Django this dictionary is referred to as 'context') and then render a template from the context into HTML by calling the template engine for that framework.
Your function will just return the HTML to the framework which will then format it properly as an HTTP response and send it back to the client browser.
Simple!
UPDATE: Here's a description of how to do wizard style multiple-step forms in Django that should help you out.