Hacker News new | past | comments | ask | show | jobs | submit login
Learn web development: Django Web Framework (developer.mozilla.org)
290 points by farabove on Feb 9, 2017 | hide | past | web | favorite | 51 comments

If you're curious about how to set up a modern JS frontend on top of Django, I wrote up a tutorial recently. It might be helpful if you're debating between trying a Single Page App approach or some other design: https://medium.com/@theSquashSH/reconciling-djangos-mvc-temp...

To easily make a modern feeling frontend, whilst taking advantage of Django's backend, and without taking on all of the complexity of frontend SPA focused frameworks, I can highly recommend IntercoolerJS: http://intercoolerjs.org/

Clearly it depends what your use-cae is, but for a large class of apps that you'd build with Django it feels just right for me: http://intercoolerjs.org/2016/10/05/how-it-feels-to-learn-in...

Not to go too far off topic, but I wish intercooler were just built into html6 or bootstrap. It's full of all the most common things that you wish you didn't need to write a full js app to do.

And if you're going down the React + Redux + REST framework path and need a boilerplate to start off on, I'd highly recommend Seedstars': https://github.com/Seedstars/django-react-redux-base

Looking only at the JS part of this boilerplate and the amount of dependencies I think to myself: "this cannot be right". It reminds me of my early Java days with bad system frameworks which needs a tremendous amount of boilerplate to get running. Maybe it's the right way to go for big production systems, nevertheless... don't like it much. But on the other hand it looks pretty complete regarding tests and there is not much to add.

Care to share why?

My apologies if you have street cred in the field, but I don't know you, so have no reason to trust your recommendation. Please tell me what makes this particular project better than any alternatives.

No street card to offer --- just a developer passing on some knowledge. I've been using Django for the past two years and React + Redux for the past year. I've scoured around for boilerplates and that's the one that worked for me the best. YMMV


I've been using react for various components inside a somewhat standard django application through https://github.com/owais/django-webpack-loader . It works by having your webpack pipeline spit a webpack-stats.json that a django's template tag reads and uses to output things in your template.

The setup is not really straight forward, and generally I have problems mixing django static files in my .scss url() , so this is far from perfect. I'm using it with a main .ts file that requires various components based on the class of body tag, so I can use this in simple reload request use case. Also I've complicated things a little so my webpack bundles are collected as other static files and my static template tag also works.

But yeah, using react in typescript and sass in this way for the frontend has accelerated my development a lot.

I think one important lesson here is that by abandoning the traditional SPA approach, you're also opening up your site to be indexed by search engine crawlers much more easily.

this is something i struggle to understand. especially with SSR/isomorphic rendering.

the vast majority of websites that need indexing should not need JS to create the html.

the vast majority of web apps that benefit from being SPAs are behind some form of login/auth and so do not need indexing.

yet there's this obsession with writing SPAs that can be pre-rendered for better indexing. i only assume this is a solution to the desire of using nodejs and javascript as a server-side language regardless of merit.

Some sites are a combination of content (blog, products etc) and a login area with a complex UI. A SPA works well for sophisticated user interfaces but is overkill for content that is just for reading. But then you have to decide is it worth jumping back and forth between JS and your server side language (Java/Ruby/Python) or maybe it would be nice to just have one language to rule them all...

Well, this is exactly what I was looking for. I am still a pretty new, self taught developer, and during my trials and tribulations I fell in love with python and django. Now it seems React is the cat's meow, so I have started to look into it and was wondering how it could work well with Django. Than k you

This is a great idea. I'm currently using the SPA + granular API method for my Angular + Django projects. It's working well enough, but your method seems much more elegant, I can already imagine the benefits. We also have a team currently looking for the best way they can integrate PHP and React, and I'm going to share this with them. Thank you!

The tutorial mentions server side rendering is easier using this approach, but doesn't mention how it is done.

Since the html output is minimal, presumably you require something like python-react that pipes the output through a nodejs server?

Presumably building the same in a React SPA using Django, that would also mean maintaining the routing system in two different frameworks at once?

Great to see Mozilla supporting Django. But isn't the official Django tutorial cover all of this, Why not just link to it?

Django's basic tutorial is great to get started, but once you get into the nitty gritty I find myself often going to stacks rather than the docs to get the information I need because the docs get kinda sparse.

One example is if you want to forgo modelforms and pass the information from the forms to the model manually through your view (for example because you want to manipulate the information before passing it to the database). I couldn't find anything in the tutorial that gave clear instructions on this and had to go to stacks to find an example. Maybe the solution is simple and obvious for most experienced programmers, but ordinarily the django tutorial explains things clearly so even newbees like me can get into it so it was disappointing that this was not done in this instance.

Another example is sessions, here is the sessions in the official django docs -


it's great on how to configure and set up sessions, but as soon as you get to how you use sessions in views it gets vague, confusing and way too sparse for what its trying to explain. I didn't know how to use sessions after reading it.

I think the Django docs are pretty comprehensive in the scheme of things. Maybe not perfect but better than average in this space.

I would definitely agree with that, the first we program I tried to work with was PHP and I think I might have given up on programming altogether had I not discovered django with it's much better documentation.

I appreciate what they have done and appreciate the time and effort the Django team put into their documentation, but more is always better and I think other independent contributions on how to use django are also needed, especially since most of the published books you can find on how to use django are out of date

I'm not trying to be argumentative, but to me https://docs.djangoproject.com/en/1.10/topics/http/sessions/... is pretty thorough. Did you come into Django knowing Python already?

You should consider contributing to the docs if there are things you think could be clearer or more thorough. It's a great way to get your feet wet in OSS, and really helps the next person.

How did you solve the problem of bypassing modelforms? Same roadblock here...

you reference the model in the view and then tell the view to save it directly to the model using the "model = form field" type syntax to assign value and then .save() method to save.

In the form field you are saving from, you write the form field value and then an empty space where the input value goes sort of like "form.cleaned_data.get("field name", " "). The second blank ""is the empty space where the field value goes. The claned_data is django's internal form validator. That sounds confusing so I'll give an example

This is what your views would look like

    from django.shortcuts import render

    from sample.models import Test

    from sample.forms import TestForm

    def Example(request):

       if request.method == 'POST':

           form = TestForm(request.POST)

           if form.is_valid():

              testmodel = Test()

              testmodel.modelfield1 = form.cleaned_data.get('formfield1','')

              testmodel.modelfield2 = form.cleaned_data.get('formfield2','')

              return render(request, 'sample/nextpage.html') 


            form =TestForm

            context_data = {'form':form}

            return render(request, 'sample/testformpage.html', context_data)

"The second blank ""is the empty space where the field value goes."

I'm not sure I understand what you're saying here, but I don't think this is right. cleaned_data is a dictionary, and so the second argument to get is a default value to use if there is no value corresponding to the key. So, in your example, if there's no value for "formfield1" in cleaned_data, it would return a string with a space in.

This is probably not what you want to do. cleaned_data will always contain values for declared form fields, so the only way the default would be used is if you've made a mistake in specifying the key (for instance, if there's a typo and you've written 'formfeild1' instead of 'formfield1'). If you've made that kind of mistake, you don't want the program to continue using a single space instead of the valid data (you'll lose data) - you want the program to report that there's something wrong.

So I think you should probably use

which will do the same thing if formfield1 is a real field name specified in the form, but will raise an exception if it isn't.

Sorry typo, it should be the second blank is the empty space where the user input goes.

I just tried your solution with cleaned_data["formfield1"] instead of cleaned_data("formfield1","") and it didn't work for me, it came back with the following error message when I submitted the form:

>'builtin_function_or_method' object is not subscriptable

I think you have to have the empty quotes after the form field and I think that's what's capturing the user input

so here "form.cleaned_data("formfield1","") seems to be telling django the form name and then the second field is where the associated user input goes which is then passed to the model.

wait just tried the code again, you were right, I don't need the second empty string. I was using [] with get and it wasn't working.

so it seems the right way is form.cleaned_data.get('formfieldvalue')



if you don't want to use get

Alternative is to use the modelform but not save the created/updated model automatically. Then you modify the resulting model object and save it manually as needed.

Works also with models with m2m fields with Form.save_m2m().

Thank you

This is helpful and gives me some new ideas to try. Thankyouverymuch

This is an order of magnitude more detailed, IMO.

Mozilla are really explaining the details between the lines here.

I had used Django back in version 1.3 and was just thinking today of how I need to brush up, as it has been a few years.

The timing of this article couldn't have been better. Now I've got my weekend cut out :)

Everything about Django 1.8 and above blows everything below away. Its all the same, but so much better. The admin app keeps getting better, migrations are a first class citizen and make ongoing change management and deployment a snap.

If you want to make a solid, stable web-app Django is a perfect backend.

This is so true. Point in case - Instagram also runs on Django!

Django is such an important building block of the web, it completely deserves this tutorial on MDN.

As someone who came to Django quite late, I cannot stress enough how coding in Django is refreshing. Yes it's not about microservices nor it bring all the trendy technologies that we all hear about.

And that's just fine, you get things done with it and at the end of the day this is what matters.

Dumb question, why does the guide suggest that you create an empty folder and then initialize the project from there? (django_test/mytestsite, locallibrary/locallibrary)

As far as I can tell, no file, hidden or otherwise, is left in the outer folder.

I'm not sure if they do this in the tutorial, but it's a convention that some people use to have the virtual environment next to the project folder in that parent folder so that you don't have to gitignore it (just have the repo in the project folder).

This is pretty fantastic. I was just thinking about diving into learning Django for an idea I want to build so this link is timely.

Best Django tut I have seen

This looks fantastic! May I suggest some syntax highlighting so the code boxes don't look so drab, though?

It has been years since I have used Django - do they still expect everything in the model to go in a single file or can you put each model in it's own file now?

Create a models.py and import there your models from wherever they are. This should do the trick.

Yeah, or another way of splitting up huge models files is to convert models from a module to a package by making a directory models and adding models/__init__.py, models/foo_models.py, models/bar_models.py then doing

from .foo_models import *

from .bar_models import *

in your __init__.py

Separating models like this is a hint that you may need another app. It has happened numerous times with me now that my models.py gets large and unwieldy, I spends a hour breaking it all out and then I realise my one big God app needs to be 3 smaller ones.

Totally agreed.

Is Django restful in current version? Or I still need these if request.GET and if request.POST ?

So, there are a few ways to handle it. DRF gives you a REST-oriented paradigm to work with, but in standard Django, you can do class-based views with either get, post, etc methods, or you can use generics like "ListView" and just provide some stock methods like get_queryset to flesh it out.

Oh man, this is far superior to the official Django tutorial I think. MDN really does a good job at holding your hand through the process.

There are moments when going through docs where way too many assumptions are made about what I know. This is where prerequisites and objectives really help out. I know what I am getting into before grokking.

They also released a similar one about NodeJS + Express at https://developer.mozilla.org/en-US/docs/Learn/Server-side/E... both are very good at hand holding and helping you out.

The learning sites from MDN are very good. ;-)

Huh. Makes me miss php

Could you please elaborate on why it makes you miss PHP?

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact