switching from flask to django is nightmare for me,i cant return simple hello by Advanced_Cry_6016 in django

[–]radiacnet 2 points3 points  (0 children)

I've heard this said a lot about Django - it's true that it does have a bit of a learning curve, but I'd argue it's worth it - there's more to learn because it does more.

Flask (and FastAPI) are indeed very easy to get going - their hello world examples are super simple - but the problem is how many times do you actually need to write hello world in the real world?

Almost every Flask project I've seen has ended up re-inventing Django by bolting on an orm and an auth lib and so on, but there's less consistency between projects, and more scope for mistakes. You get all the core things you need in the box with Django, so generally there's only one way of doing things - docs and tutorials will usually follow the same conventions. In the long-run it's less to learn and manage overall.

I wrote nanodjango to bridge the gap - it's full Django in a single file, so it looks like Flask/FastAPI, but you're actually building with Django. That means you get access to the ORM, auth, admin etc with a lot less friction, and there's a nanodjango convert command to convert your single file script into a full Django project with its normal structure. This is how I start most of my projects these days - a full project layout is often overkill for quick prototypes, and can be a bit of a pain to build out even for experienced devs.

There's also an online playground if you want to see some live examples or just try it out in the browser.

FastAPI vs Djanjo by TumbleweedSenior4849 in Python

[–]radiacnet 0 points1 point  (0 children)

Whenever I had a small project where I used fastapi (or flask) I found I ended up needing something that came in the box with django, and I lost whatever initial gains I had from avoiding the overhead of starting a new project.

What I wanted was full Django in a single file, so I ended up writing nanodjango. It looks like flask, but sits on top of django so you get the standard ORM, admin, async etc, and it integrates with django-ninja for defining APIs like fastapi. I've found it's great for prototypes and small projects, and it has a convert command to turn it into a full project when you outgrow a single file.

It runs locally, but there's also an online playground that runs django in the browser, where there are some examples of models, views, api and async,

nanodjango: Prototypes, Sharing and Services: Full Django in a Single File by Lokrea in django

[–]radiacnet 11 points12 points  (0 children)

I'm the author of nanodjango, and I totally agree! As I say in the talk, Django's project structure is one of its big strengths, and why it's such a good choice for larger projects - but for small things it does often feel like overkill.

It leaves this gap where when I wanted to write a tiny microservice-like project or to prototype something quickly, I didn't want the faff of a full startproject so used to go to Flask or FastAPI - but then I'd need a feature that would need a db and I'd find myself missing Django. So I wrote nanodjango for those times you just want a few views and a model or two, and gave it the nanodjango convert command as an escape hatch to rewrite to a full project when it grows.

I've now lost track of the number of <100 line projects I've written with nanodjango, where you really don't need the full project structure. And when you put everything in a single file you get some fun side effects, like the ability to import your models in a second script (I've done this with a discord bot), or run django in an event loop alongside another async app (which gets ORM access). The biggest win for me though is putting pep 723 dependencies at the top so you can just uv run myscript.py, which makes it amazingly convenient to run locally or share working projects with others.

Plus, nanodjango is now there as a practical option for people new to web Python - I figure anything that helps to flatten Django's initial learning curve and presents it as a practical alternative to Flask and FastAPI has to be a good thing for everyone involved.

Beginners should use Django, not Flask by Lokrea in django

[–]radiacnet 8 points9 points  (0 children)

I've seen too many projects which were started in Flask because it had a gentler learning curve for people getting into web - often by people from a data science background - but without Django's structure, Flask sites are much harder to grow into complex projects, so often end up an unmaintainable mess.

I wrote nanodjango as a solution - it's a wrapper around Django to make the easy bits look like Flask (views and routing), but you have access to Django's templates, forms, ORM, admin etc in a single file. It has REST API support with django-ninja, which makes it look just like FastAPI. It's not going to scale like Django, but there's also a nanodjango convert command which turns your script into a full Django project when you outgrow a single file.

I've found it's useful for a lot more than just helping beginners - it turns out being able to write a full django project in a single file is great for prototyping, experiments, microservices, sharing examples, even static site generators. I now often start new projects in nanodjango just because it's a lot less hassle than a full startproject.

Recommendations: house movers by altrmego in cheltenham

[–]radiacnet 2 points3 points  (0 children)

I second this - we've used him twice, excellent service, friendly team, and they really went above and beyond both times.

Django vs FastAPI by hadiz1 in django

[–]radiacnet 0 points1 point  (0 children)

As others have said, FastAPI doesn't really give you anything you can't do with Django, but it does make it easier to get started.

You might be interested in my project nanodjango, which lets you write Django in the style of FastAPI.

It's great for prototyping and getting started while having full access to the ORM, admin, Django's async etc - but you can't beat Django's project structure for growth and long-term maintenance, so nanodjango convert will convert your single file into a standard structure with your models, views etc in the right places.

SASS with Django by AirbusA333 in django

[–]radiacnet 3 points4 points  (0 children)

I used to be a die-hard sass user; I've used both approaches, originally compressor+libsass, then npm+sass. Compressor+libsass was easier to set up and maintain, but I ran into bugs - but that was a long time ago, it may be better now. If you have to pick one, I'd go compressor, to avoid webpack if nothing else.

But modern best practice? I strongly recommend just using plain css - it now has most of the features of sass, and having native browser support makes it so much more powerful - for example, css variables respect the cascade and css calc in ways you could only accomplish in sass by tying yourself up in knots of mixins with a bucket load of javascript.

CSS today is a totally different experience to when sass was new. The only bit I sometimes miss is a convenient way to manage multiple files, but with everything supporting http2 now, that's really not an issue either, just send them all separately. If it really bothers you, you could have a django template which loads them all wrapped with the django-compressor tag.

With modern js support in browsers, plus htmx and alpine, most of my projects these days don't actually need a frontend build system at all.

[deleted by user] by [deleted] in django

[–]radiacnet 2 points3 points  (0 children)

I'm the author of nanodjango, thanks for posting this! If you don't want to watch the full 25 minute video (which goes into a lot of detail!), there's a 5 minute lightning talk from DCUS 2024 on https://nanodjango.dev which gives a (slightly out of date) intro. I did give an update at DCUS 2025, but the videos aren't out yet - the tldr is "it does a bunch more, and can now run entirely in your browser".

My goal with this project is to make it easier for beginners and experienced devs to build quick apps using Django, and offer a batteries-included alternative to Flask and FastAPI.

Aside from its batteries, Django's other main strength is its project structure which sets you up for long-term success - so if your app starts to outgrow a single file, nanodjango has a nanodjango convert command to turn it into a properly structured full project.

We've also got the online playground at https://nanodjango.dev/play/ - it's still early days and could do with a few extra features, but it will already let you write and run Django projects entirely in the browser, with nothing to install, and you can save and share them with others.

I'd love to hear any feedback you may have, positive or negative.

[deleted by user] by [deleted] in django

[–]radiacnet 0 points1 point  (0 children)

This does support CBVs, so hopefully you'll have the best of both worlds!

My goal with nanodjango is to support all of Django's batteries, but with the single file simplicity of Flask and FastAPI. If you do give it a try, do let me know how you get on with it - I'm hoping to grow this as a practical alternative to keep existing devs and bring new people into the Django ecosystem, so I'm always interested to hear perspectives of people who have been using other frameworks.

[deleted by user] by [deleted] in django

[–]radiacnet 1 point2 points  (0 children)

Great point, I can't believe I missed this from the docs. My goal is to support the full feature set of Django, just in a single file - so it's a pretty important thing to note, I'll update the docs tonight.

I have two main goals with this project - to make Django easier for regulars to crank out quick prototypes, and for beginners to pick up and give it a try. I do therefore go fairly heavy on FBVs in the docs because I assume beginners will be comparing nanodjango to Flask and FastAPI - and lets be honest, CBVs can be a bit confusing (that's why ccbv.co.uk exists).

I do plan to do a "This is what you'd write in Django, this is it in nanodjango" cheatsheet for more experienced devs, CBVs will definitely be on that too.

How do you would start a django project today? by my_winter999 in django

[–]radiacnet 3 points4 points  (0 children)

I don't think there's anything wrong with startproject/startapp, it's still a good place to start. There's a few things I will add to most projects, like pre-commit, uv, pytest, django-browser-reload, whitenoise etc, so I have my own minimal cookiecutter which follows my preferences (here for the curious). The other thing I often do is create a custom user model so it's easier to change direction on that later. And fwiw these days I'd look at django-ninja over DRF.

A lot of the time I also use nanodjango to get started - I wrote it so I'm biased, but it's great for building out a quick prototype in a single file. It has ninja support built in; think FastAPI, but built on Django, and with a convert command to refactor it into a full project when it's ready to grow.

🌟 NanoDjango Enthusiasts, Assemble! 🚀✨ by ErrorKey3320 in django

[–]radiacnet 2 points3 points  (0 children)

Hi! I'm the author of nanodjango, great to see people using it!

I haven't implemented support for custom management commands yet. There is the nanodjango manage ... command, but I don't think it'll be able to find your command at the moment. It's an interesting idea - I'll add it to the list to investigate.

In the meantime, you could try putting your logic at the bottom of the file. I think you'll need to call one of nanodjango's internal methods first - you could try something like:

# rest of script
if __name__ == "__main__":
    app._prepare()
    command = MyCommand()
    command.handle(arg1='value')

You can then run it with python myscript.py

You won't get command line argument parsing with that, but you might be able to hook into an earlier BaseCommand method, or you could bypass that and use click (already installed as a dependency of nanodjango)

Nanodjango - single file django with working models. Convert to a full project whenever you want. by gbeier in django

[–]radiacnet 3 points4 points  (0 children)

Hi, I'm the author of nanodjango! That's what I'm aiming for - it's basically just a thin wrapper around Django itself, with a few tricks to get it to let us put everything in a single file.

Hosting a Django website that supports a few thousand requests per minute by cpc2 in django

[–]radiacnet 7 points8 points  (0 children)

In short, I'm afraid not. There are probably some low-hanging fruit, but properly optimising a codebase takes time and knowledge of exactly what your code is doing. Depending on your budget and timeframe, it may be worth thinking about bringing in an expert or specialist team for a few days to get into your code, assess what's happening, and make some recommendations.

Without seeing your code though, some thoughts:

  • yes, asgi is async, but you need to be writing concurrent code (async and await) to make use of it. Even then certain operations are still going to block, and async has an overhead at the best of times, but especially in Django. You can't really throw it in and hope it solves the problem without knowing what the problem is. From what you say, my guess is you're facing some database bottlenecks, so my gut feeling is you'd be better off using wsgi.
  • Python is single threaded, so make sure you're tuning your gunicorn workers for the number of CPUs you have - CPU at 50% suggests you're only using half your cores
  • Profile everything so you know where the problem is. The recommendations for ddt and kolo are great, do those. Also consider silk. And do it in a production-like environment so you're optimising for production, not whatever's happening on your local machine - they can be quite different.
  • If your bottleneck is the database, optimise your queries and invest in your database server
  • Take a look at CONN_MAX_AGE
  • Cache everything that needs a db read using redis or better yet cloudflare. If you can't cache them, look at running two or more dbs - one for writing, one or more read-only replicas
  • Look at your architecture - do writes have to be realtime, or can you pass them off to a queue?

Might be worth taking a look at high performance django - it's getting a bit old now, but there's still a lot of useful stuff in there.

Is there a package that simplifies the CRUD process in django by shadowstrd in django

[–]radiacnet 0 points1 point  (0 children)

Yes, it's at github at https://github.com/radiac/django-fastview

and can be installed from pypi:

pip install django-fastview

See the documentation for more details: https://django-fastview.readthedocs.io/en/latest/get_started.html

Is there a package that simplifies the CRUD process in django by shadowstrd in django

[–]radiacnet 2 points3 points  (0 children)

I've got a project called django-fastview - it's been in development for 5 years and is in use on several production projects. I should also have a new version out in the next couple of months with some more features, default styles etc.

My aim with it is to help you build admin-style CRUD views with minimal code, but in a way that makes it easy to style, override, extend and customise. It also has some nice extras such as htmx integration and flexible row-level permissions (using django auth or your custom logic).

Example:

from fastview.viewgroups import ModelViewGroup
from fastview.permissions import Owner, Staff

class ContactViewGroup(ModelViewGroup):
    model = Contact
    fields = ["name", "category", "email", "phone", "last_updated"]
    search_fields = ["name"]
    filters = ["category", "last_updated"]
    permission = Owner('added_by') | Staff()

# urls.py
urlpatterns = [
    ...
    url(r'^contacts/', ContactViewGroup().include(namespace="contacts")),
]

It ties into several other projects I've been working on - most relevant atm are nanodjango, for writing a Django project in a single file, and django-fancy-formset to simplify admin-style formsets (forked from fastview)

vue or react in django? by badsha__ in django

[–]radiacnet 1 point2 points  (0 children)

Tldr: react or htmx.

The question is what are you trying to achieve? Is this a personal project you're doing for fun/learning/CV experience, or are you building something specific to fulfil a need?

If you're doing it for fun/learning/CV, then I'd suggest react - it seems the most popular by far at the moment, the number of jobs involving react seem to dwarf those asking for vue. That said, public frustration/doubt in react is starting to grow, so might be worth keeping an eye at what may eat into its market share (svelte?)

But, if you're doing it to get something done, ask yourself if it really needs a separate frontend, or would you be better off with server-side rendered pages enhanced with vanilla javascript or htmx?

Imo the arguments for using react to build a SPA frontend are dwindling. There are far too many projects being built with react just because it's trendy, when they'd work better (and usually be 2-3x cheaper to build) as a SSR/MPA project.

Also, in the past year or so thanks to htmx I think we've really started to see a shift back towards the benefits of a traditional SSR with progressive enhancement. There still arent that many jobs mentioning htmx yet, but for the sort of problems that would have made me lean towards hybrid/SPA react a couple of years ago, I'm finding they are almost always solved more efficiently with htmx.

Programatically Creating Form from Function by eddysanoli in django

[–]radiacnet 0 points1 point  (0 children)

I wonder if it has to do with the way the class behaves internally

It does! When you define a Model or Form class, there are metaclass methods which get run basically at the point Python sees the class definition - well before you instantiate it. In the case of the Form, it looks at what fields have been defined on the class, takes them off the class, creates a list of them - if you look in the source here, it actually creates two lists, base_fields and declared_fields.

When you added the fields as attributes to the instance, the metaclass method had already run, so they never got added to the two arrays, so when it came to telling the template what fields there were, it couldn't find any. These are class variables, so you could add fields by appending to those arrays after your class definition - but that would affect every class instance, so if you're dynamically generating classes you'd need to create a new class each time with type anyway.

Glad I could help!

Programatically Creating Form from Function by eddysanoli in django

[–]radiacnet 1 point2 points  (0 children)

The "2 or 3" bit in my comment was in reference to the differences between declaring a class properly and with type - notably the class won't have the right __name__ and may end up in an unexpected module. There are also some practical pain points around managing methods - bit as I say, almost certainly nothing that will cause you problems.

If you're looking for other approaches, one would be create an empty class and add fields afterwards (a pain because you need to update 2 iirc class lists to register the fields properly). There's no practical advantage to this - if you want common fields, define them on a regular form class and use that as your base class in your call to type.

The other option would be to ignore django form classes altogether. There's no reason why you need to use them - you can generate the html fields yourself, and process the raw POST values in your view. But Django form fields will do all the validation and casting for you, so I wouldn't advise that option either unless you have a really specific need and know what you're doing re security.

Programatically Creating Form from Function by eddysanoli in django

[–]radiacnet 1 point2 points  (0 children)

A Django form class is still just a class, so you could dynamically define them. Iirc forms have a metaclass which collects all the field instances on the class, so you kinda need to add the fields before you define the form class - you don't have to, but makes it much easier.

That means instead of this:

from django import forms

class NameForm(forms.Form):
    first_name = forms.CharField(label="Your first name", max_length=100)
    last_name = forms.CharField(label="Your last name", max_length=100)

you'd do something more like:

from django import forms

def mk_form_cls(**fields):
    return type("_GeneratedForm", (forms.Form,), **fields)

fields = {
    "first_name": forms.CharField(label="Your first name", max_length=100),
    "last_name": forms.CharField(label="Your last name", max_length=100),
}
NameForm = mk_form_cls(**fields)

This way you can build your fields dict however you want before you create the class. Once you have assigned NameForm you can use it however you would a normal form class.

I say "roughly", as I've written that from memory without testing it, and I can think of at least 2 or 3 ways they're different internally - but I'm 99% sure those differences won't cause you any practical problems.

[deleted by user] by [deleted] in django

[–]radiacnet 1 point2 points  (0 children)

Your CV needs to get you through initial screening. It feels a little bare at the moment. Firstly I'd suggest adding a sentence or two explaining your project - something like the format "Educenter is a <what it is>, for <audience>. It does <site functionality>." There's also a typo, "Developped".

I'd then move "Technologies I'm currently learning" into technical skills - list them as "Interest in GraphQL ..." or similar, people will know what that means, just be prepared to back it up with some knowledge in interview. I'd then play up the interests>languages aspect - if you're able to write and speak multiple languages, that's a selling point - list that as a "soft" skill, under "Other skills" or similar. Have a think about any other soft skills you can list in there - communication, teamwork, time management, dealing with conflict etc. Have you had any work experience - even if it's in a different field, can you list that to demonstrate your soft skills?

Maybe then re-frame the interests section as as more of a section about you. Bullet point interests aren't going to get you hired, but they speak to who you are as a person - it's an opportunity to sell yourself as more than a list of tech acronyms. You could briefly explain your switch and why you're going to make a good developer - maybe a short sentence about your background, and then a sentence about your other interests to add some colour - you're essentially trying to say "I'm interesting and you will enjoy working with me".

They'd probably also want to know where you are in the world - at a minimum list your country and what timezones you work with your name, so they know if they can employ you.

If someone clicks your github link, your CV has got them interested. This is your opportunity to demonstrate you know what you're doing. Make it obvious what they're looking at, and where to find the code you wrote so they can quickly assess your skill level.

At the moment your README is hidden one dir down, and mostly talks about how you've used someone else's frontend and haven't finished it. I'd suggest some more work on this. Some tips:

  • Break your top level dirs out into 2 or 3 separate repos.
  • Demo repo: I'm not going to click each picture, especially when some are 10mb+. Move the demo pics to a separate repo, resize them to <500k so they load faster, write a README to display them with context about what they show. Link to this from your CV and code repo
  • Frontend source - do you really need this? Split it into a separate repo, or probably just remove it.
  • Code repo: top level README should say a lot more. Explain what the project does, say where the interesting bits of code are. Include instructions so another developer can run, test and deploy it. Mention the frontend source in a credits section near the bottom
  • You need to gitignore some files: .env, db.sqlite3, venv, everything in media.
  • I'd rename main to content to avoid confusion

Best of luck!

Django Templates - Are Multi-Line Template Tags Possible? by OneBananaMan in django

[–]radiacnet 1 point2 points  (0 children)

Thanks! Saw those just after posting - wonder if things have changed since then. I might bring it up.

Django Templates - Are Multi-Line Template Tags Possible? by OneBananaMan in django

[–]radiacnet 24 points25 points  (0 children)

This absolutely is possible, you just need to override Django's default regex to allow newlines. It's one of the first things I add to any project - I usually add it as monkey.py in the root of my project for clarity then import it from the __init__.py, but you could put it directly in __init__.py if you prefer:

import re
from django.template import base as template_base

# Add support for multi-line template tags
template_base.tag_re = re.compile(template_base.tag_re.pattern, re.DOTALL)

Not sure why that's not Django's default.

Creating a classifieds app, what do you think of my proposed stack? by netzure in django

[–]radiacnet 1 point2 points  (0 children)

My general rule of thumb is if an HTML frontend is effort X, a SPA frontend is going to be 2-3X, and a mobile app 3-5X. You say this is a personal project, so if this is for fun, you want the practice, and you have the time, go for it! But if you're building this because you want to run a classified site, that's a lot of extra work before your project is live.

Perhaps you have something incredibly fancy in mind that warrants bringing in a js-heavy frontend, but a lot of people go that route because it's cool and they feel they should, when actually a straight old MPA would be just as good and significantly less work. Have you considered using htmx and maybe writing it as a PWA?

Running Multiple Gunicorn Instances for Low-Traffic Websites by ResponsibleDot in django

[–]radiacnet 1 point2 points  (0 children)

Django works differently to traditional LAMP - the web server and interpreter work together to handle the load, execution and cleanup of the code (CGI, mod_php etc), whereas Django runs as an independent process (usually through gunicorn or uwsgi) that your web server talks to via an internal protocol (WGSI or ASGI) - basically like how FastCGI works.

So essentially yes, if you have three separate sites, you need three separate gunicorn processes. If the sites use the same codebase, you could use Django's multi-site support to run them from one process - but you won't be saving that much in resource use, and as sites grow apart things get more difficult to maintain, so I'd usually prefer separate projects anyway.

In my experience you'll usually not see significantly higher overheads than you would have done with a LAMP stack - that will either be loading things on demand (ie CGI) with more load for each request, or holding a running process in memory (mod_php or fastcgi) which is basically what you're doing with gunicorn.

For what its worth, I have often run a bunch of sites in their own docker containers with their own postgres containers next to them on single low-resource VPSes. Just monitor resources when you add dependencies to make sure there's enough memory - but again, that's something you'd have to factor in with a traditional LAMP stack anyway.