Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

  1. 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
  2. Django is hooked up to a Postgres database
  3. (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!

like image 207
kmypwn Avatar asked Mar 04 '23 01:03

kmypwn


2 Answers

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.

like image 128
funnydman Avatar answered Mar 05 '23 16:03

funnydman


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.

enter image description here enter image description here enter image description here

like image 43
JSRB Avatar answered Mar 05 '23 14:03

JSRB