What is the "best" way to build a Django Webapp frontend? [closed] - django

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Thanks in advance! This is more a "philosophical" question then a direct request for opinions on code, though I would greatly appreciate anyone's input on code examples to look at.
I've been a "traditional" developer for as long as I can remember, and now I work professionally as a data scientist. That being said, the one frontier I've never truly touched is web development.
For a project I'm working on, I need to build (and in a somewhat expedited timeframe) a good-looking web application that functions somewhat similarly to a Wiki website (using existing codebases like Mediawiki is not an option here, so assume everything has to be built from the ground-up).
In trying to do things the "right way", I've set things up as follows:
Django models are built that seem to correctly capture the relational structure of data for the webapp, at least as tested by playing with Django's admin portal
Django is hooked up to a Postgres database
(1) and (2) are running inside Docker containers
The most important piece here left, obviously, is the frontend. I've tried to ask several friends and acquaintances for advice, and have been pointed in the Bootstrap direction.
From here, I admit, I'm a bit stuck.
I see examples on the Django docs that don't involve any Javascript (it seems, with minimal lift, HTML pages can directly interact with the database, using what seems like a pretty simple "insert-placeholder-here" logic, as I have set it up through the Django models). I see a similar construction here and here.
But then I see a whole other set of instruction on the web about how to make a functional webapp-- creating serializers for the Django models to JSON, building a REST api, writing the frontend page logic using Javascript and using a library imported into Javascript to interact with the manually-built API(s) to interact with the backend.
Now, of course, the "first" approach seems much simpler. The second feels like reinventing the wheel-- if I can simply use a construction like {{ num_books }}, why would I go about building all those APIs and worrying about JSON? But I feel confused. Is there a "right" choice, thinking long-term? It seems like I can find people using Bootstrap and other frameworks taking both approaches. Can I not use Javascript code unless I take the JSON/API approach? Does that even matter? What truly are the differences here?
A compass on the rough seas would be much appreciated. Surely I cannot be the first to try to build a functional webapp with Django... the frontend is totally foreign to me.
Thank you all!

In the first place, Django is a framework which means that it contains already a predefined set of necessary functionality that most people need, sometimes people say "with batteries included".
Before REST architecture was invented front-end and back-end were closely related to each other. There wasn't a straight line between them and it was hard to share business logic with other services.
Basically we can say that there are two options, how to organize front-end and back-end workflow with Django:
Using Django templates:
The most simple and easiest way to get started. All that you need already presented in Django. Let's take a look at this simple example:
views.py
def index(request):
fruits = Fruit.objects.all()
render(request, 'index.html', {'fruits': fruits})
And after that you can use variables from the context in your template like so:
index.html
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>
Django template system is really powerful and customizable if the default template engine doesn't suit your needs there is a possibility to choose another one, for example Jinja.
You can do a lot of stuff there, but as a general recommendation, all the "computing" stuff shouldn't be stored on the template level because it can dramatically increase the time rendering of the page. The better place to put business logic is views and most of the work with the database on custom managers.
For dynamic parts of your application, you could use AJAX probably from JQuery library.
It's also quite simple to work with forms, Django by default handle it with csrf protection. Default validators and model forms give you real power.
When you use templates you depend on them, most likely you couldn't reuse your endpoints somewhere else and that's why you need REST. Django has a little set of features that can help you with it and most likely you would end up with django-rest-framework usage which one of the most popular libraries used with Django today.
Using REST architecture:
The example above would look like this, though there is ModelViewSet, which do the most of boilerplate stuff for you:
class FruitViewSet(viewsets.ViewSet):
def list(self, request, *args, **kwargs):
fruits = Fruit.objects.all()
ser = FruitSerializer(fruits, many=True)
if not ser.is_valid():
return Response({}, status=status.HTTP_400_BAD_REQUEST)
return Response(ser.data, status=status.HTTP_200_OK)
You can use ModelSerializer or write your own serializers. The validation process is simple and straightforward:
class FruitSerializer(serializers.ModelSerializer):
def validate(self, attrs):
# validate your data here
pass
class Meta:
model = Fruit
fields = '__all__'
To display this data on a web page you could use whatever you want, vanilla javascript or any javascript framework which supports REST, the most popular today: React, Angular, Vue.
With REST you could use the same API for your web, mobile application and so on. In the end, implement once use everywhere.

As soon as you want to have dynamic parts in your frontend, you will need Javascript at some point. To fasten up development I highly suggest to use a framework like Vue, React or Angular. They have dozens of tools to use for particular needs within your project. Also you might look into jQuery when using Javascript.
I am currently building a Django web application myself (started like 3 months ago). I use Javascript a lot to manipulate the Django rendered templates.
Why Django might be your right choice
The nice part about Django is the Model-View-Template architecture which by my opinion is an excellent framework for your wiki app. You request a http, Django fires the linked view-function and renderes the template - et voila!. And if you need data transmission from/to PostgreSQL you just build a model and include the data calls into the view-function to use the data on the frontend.
You won't have to build a user management system (built-in
django-admin)
You will have a lot of frontend required business logic included in the Django orbit
No need to worry about JSON. You just fetch the data from the database using python objects and work with that data in the frontend. If at some point json would be a better choice for whatever reason, you just manipulate it with a Python serializer.
It is pretty easy to deploy/publish a Django based application using e.g. digitalocean.com or heroku.com
Since this was some broad question, I hope I could provide you some hints on how to proceed with your development. However, feel free to comment this post for further questions.
To give you a brief feeling I will attach some snippets of my current project, using basic HTML, CSS and Javascript along with Django as the python based backend.

Related

How to make editable fields in frontend for Django objects

I need to make objects editable in frontend by clicking on it and enable a form field to edit the text. i.e. in a ToDo-list which tasks can be edited by clicking on the task like shown in the following graphics:
I am working with Django 2.x and unfortunately, I'm a little inexperienced.
Is it a good practice to realize this with REST API and/or Angular/React?
I would be glad about a few experiences, how something is feasible.
I have found a good solution to implement the desired functionality with Jeditable
https://github.com/NicolasCARPi/jquery_jeditable

Determine which templates are used by which views/ URLs in django

I have a fairly large django project consisting of several individual apps. I am farming out some of the front-end work (CSS, HTML tweaks) to people who aren't over-familiar with django. To that end I'd like to generate a list of templates for each URL pattern any given engineer is working on. This will save much time that would otherwise be spent manually tracking down the templates used during a view's render phase.
For example, if Bob is working on URLs beginning with /accounts/ then I'd like to generate a list of all the templates used by any view that handles requests to those URLs.
My initial thought is to use something in the test framework since that has access to the templates rendered during a request. However, I can't guarantee that all URLs or views will be exercised (sadly I don't have 100% test coverage), and a missed template is unlikely to be noticed. I don't mind writing a set of tests that simply exercise each view, but don't want to duplicate existing efforts. Also certain views require POSTed data or authentication to function correctly - although I suspect that's an issue I'll have to face no matter what approach is used.
Are there any utilities or snippets that will do what I need?
django-debug-toolbar is a must for developing with Django, It includes a panel detailing all templates used during a request.
I've found the SQL panel is the most helpful for improving page load times as it details slow and duplicate queries.
It can slow down requests when enabled, disabling all panels but those that you use helps.

Django project applications division

I'm currently writing django project and got confused when it came to separation into apps. Project consists of posts and categories which are kept in one app, also there is a 'main' app which handles user profile view, login, logout and registration. Now I'm trying to implement user-to-user messages and I'm wondering if it should be kept as separate app.
If Message model is kept in application 'messages' how do I realize show_messages view?
1) It seems that it should be stored in 'main' app since it's linked by my_profile view. It would just get all Message instances form 'messages' app and render template extending profile.html or including from 'messages' app a partial template responsible only for messages listing. But why would I then need separate application just to hold one model there with some helper functions?
2) Secondly I wonder about placing show_messages view in 'messages' app but then I would need to use template which extends template from other application which again seems to be violation of self-containment rule. Also all "accounts/" urls are currently kept in main.urls so I feel wrong about adding "accounts/profile/messages" rule to messages.url.
3) Finally I think about moving Message model with all helpers and templates to 'main' app since messages are designed to work with User models and views therefore forcing additional separation seems useless.
Thanks for reading my thoughts, I'll appreciate all clues and explanations.
When I first started working with Django, I found the answers on this SO question to be particularly helpful, regarding app/project layout: Projects vs Apps
Many of the answers are useful, but this one is particularly pithy:
Try to answer question: "What does my application do?". If you cannot answer in single sentence, then maybe you can split it to several apps with cleaner logic?
I've read this thought somewhere soon after I've stared to work with django and I find that I ask this question my self quite often and it helps me.
Your apps don't have to be reusable, they can depend on each other, but they should do one thing.
Interdependence of apps isn't always problematic. For example, in a lot of my projects I have a separate app that is used solely for creating dynamic menus. In order to work properly, I need to import the specific models of that site into that app -- so I couldn't just drop it into another site, unaltered, and expected it to work. Nonetheless, the other 90% of the code in that app is completely reusable, and it's easier for me to move the relevant code to a new project if its already spun out into a separate app -- even though that app only holds a templatetag and a template.
Ultimately, a django site would technically run just fine with ALL models/views/etc in one big, unwieldy app. But by breaking your project down into "this app performs this specific function" you're probably going make managing your code a lot easier for yourself.
Regarding the 'url' point in 2, there's no reason not to subspace URLs. You are already doing this in a django project already -- mostly likely your main urls.py has an include() to another app, such as your main.urls. There's no reason your main.urls can't also have an include() to your messages app.

how to make interaction between different django apps in a single site?

I have just learnt about Django apps. I want to know that within one site, if I make different apps. like, users, profiles, polls, blogs,comments, jobs , applications then how can I manage them to make them intereactive? And is it how the concept of app should be? I want to have things loosely coupled that's why asking? Rails work on the way of REST, so do Django support that also with the use of apps? May be my questions seems a bit ambiguous because I am new to django and some of my concepts are still messed up.
Please tell what ever you know.
The general idea is that apps should be as loosely coupled as possible. The goal is to have completely self-contained functionality. Now, of course, that's not always possible and many times it even makes sense to bring in functionality from another app. To do that, you simply import whatever you need. For example, if your "blogs" app needed to work with your Comment model in your "comments" app you'd simply add the following to the top of the python file you're working in:
from comments.models import Comment
You can then use Comment as if it were defined right in the same file.
As far as REST goes, Django's views are much more fluid. You can name your view whatever you like; you need only hook it up to the right urlpattern in urls.py. Django views can return any content type, you just prepare the response and tell it what mimetype to serve it as (the default is HTML).

Avoiding circular dependencies in Django applications

While working on my Django-based projects I'm always trying to follow Django's approach to reusable apps - I'm trying to decouple my applications from each other and especially trying to avoid cross references but sometimes it does not seem to be possible.
Let's consider a simple example with 2 applications: articles and users. Articles application defines article model, articles list view and single article view, users application defines user model and user profile view. Article is referencing user from the author field, so articles application is obviously dependent on users application which is fine.
But when it comes to user profile, I want to display latest articles authored by the user (and may be latest articles viewed by the user) on that page but that makes users application aware of articles application which is what I'm trying to avoid.
I can obviously try to push all such references to the template level but it still does not solve the issue completely and at the same time may be very inefficient in terms of database queries sometimes.
What do you guys do in such cases?
If you are really set on not having any conversation between the 'user' app and the 'article' app, then you need a third app to act as interface. That would know about users and articles and define all the coupling between them. Your article view would be in there, since it has to get the user data, and your user profile view would be in there, because it needs to say "Fred wrote 5 articles".
Whether this level of decoupling is worth it, I don't know. Sometimes programming for re-usability gets in the way of making the thing usable in the first place.
The standard (or preferred) way of keeping coupled apps decoupled is to add a conditional coupling - like in some apps that try to import django-notification and only if they find it, they report events to it.
Still, if you have two apps that talks to each other by design, then I don't see any point in decoupling them - there are plenty of examples in Django world of apps that just require other apps. Note that I'm talking here about writing real-world software, not about some academic delibrations :-)
It seems that in this case, the dependency of users on articles is in a method, not a field. (Whether it's a model method, a model class method, or a manager method is immaterial). If that's so, you can do a lazy import of articles inside the method. By the time this import is performed, users.models will be fully loaded, so even if this is a circular import, it will not cause problems. The "import users" statement in articles will not have to re-load users and will have the full users namespace available.