/r/django

Photograph via snooOG

News and links for Django developers.

News and links for Django developers.

New to Django? Check out the /r/djangolearning subreddit.

Django's Code of Conduct applies here, so be good to each other.

/r/django

137,738 Subscribers

3

Unittesting in django

Hello. Anybody got any links to comprehensive unittesting in Django? I've googled and browsed page after page but all I see are guides to writing simple tests for one or two applications. I'm interested in a guide that covers how to unittest in enterprise djago software, something with like 6 applications.

3 Comments
2024/11/10
08:07 UTC

1

Has anyone used lemonsqueezy for subscriptions? Any tips?

I’ve used stripe with dj-stripe before and it has a lot of built in things to make it easy. But stripe doesn’t handle tax which is a big problem if you have customers in the EU.

So I’m looking at Lemonsqueezy, but it’s unclear what the best way to set up subscription tracking / sync with django. Any tips?

1 Comment
2024/11/10
07:34 UTC

34

Code examples: building efficient REST APIs with Django

Recently I had to fix a couple django rest-framework APIs at work that were built as part of a MVP that could not scale properly, which got me thinking of writing a tutorial about different ways of writing APIs in Django.

I provided the dockerized examples that you can easily run, the README contains step-by-step changes I make to the API, starting with a toy example that struggles to return 100k rows in over 30 seconds, optimized down to under 1 second.

I know some of these are controversial opinions of Django, but I thought I'd share them any way, hopefully you pick up something useful. It's a work-in-progress, I plan to add comparison to a Django-ninja as well as backend written in pure Go, as I've come to like those two as well.

https://github.com/oscarychen/building-efficient-api

3 Comments
2024/11/10
04:38 UTC

1

Djangoworker fixup

Hi everyone,
I am developing a Django application. We implemented automation using celery-beat db scheduler to utilize third-party API for data. I am stuck with the error "You cannot call this from an async context—use a thread or sync_to_async. It occurs after the task execution sometime occurs also inside a task where ORM operations implemented. " I don't understand why this error is raising and don't know how to fix it.

  • Worker and beat running as a daemon in EC2 instance
  • Redis localhost is message broker

https://preview.redd.it/15hc3e1m100e1.png?width=1309&format=png&auto=webp&s=e89804853e915e7709f34e014275b64a364e92c2

2 Comments
2024/11/10
04:14 UTC

4

How do I maintain consistent web sockets in my Django app?

I'm developing a Django application that requires a persistent WebSocket connection to continuously fetch live data from a crypto market API. I need to keep this WebSocket connection active throughout the application's lifecycle to update my local data as new information arrives. This updated data will later be displayed on the front end, so I anticipate needing a separate WebSocket connection between the front end and back end (one connection for backend-to-crypto market API, and another for backend-to-frontend).

I'm new to this type of setup and would appreciate guidance on the best practices for implementing it. I've explored Django Channels, Uvicorn, and Daphne. Although Django Channels might be suitable for the frontend-backend WebSocket connection, I'm more focused on maintaining a robust event-loop structure for the backend-to-crypto API connection to ensure it remains alive and responsive. I'm considering building a custom event-loop manager to handle this, but I'm unsure if it's the best approach.

Could you suggest any established methods, libraries, or patterns for maintaining a continuous WebSocket connection for real-time data updates in a Django application?

2 Comments
2024/11/09
20:22 UTC

1

What is the best practice to include Bitcoin transactions

Hi, I am developing an app that shall include BTC transactions (payments, credits funding, etc). I am looking for best practices regarding crypto modelling (e g. Payment address fields). What are best practices? It's there a good plugin that I can install it do I need to write the field types for models and forms myself? Thanks for any hint!

2 Comments
2024/11/09
19:23 UTC

0

How to migrate old project from Intel Mojave to Apple Silicon

Hi all, is there any easy way to migrate an old project on Intel macOS to Apple Silicon? I did migration assistant on the Mac and everything is broken.

Project has postgresql, supervisor, celery, and Django. Anybody been down this path and could offer pointers?

21 Comments
2024/11/09
18:47 UTC

4

DSF 2025 Nominee

So I am in the DSF 2025 nominee list. It’s my second year in a row, and honestly the best thing that comes out of it is creating the awareness of DSF within my developer community.

I didn’t know about this till last year during DjangoCon Africa, and I have learned to appreciate the importance of communities especially in open source projects like Django.

So maybe if I get into the board, my mission would be getting the word out there

https://www.djangoproject.com/weblog/2024/oct/28/2025-dsf-board-candidates/

0 Comments
2024/11/09
18:27 UTC

5

Best File storage option

Hey, guys! What is the best file storage option you have worked with in production? S3, Firebase (GCP), Cloudinary, or any other options?

10 Comments
2024/11/09
18:19 UTC

3

Do you use types annotations in your Django project?

I don't have a Python/Django background, so my question may sound pretty weird.

Do Django developers use Python type annotation to enforce type checking (the TS way) ? I'm not sure there is a consensus about this, but I'm curious.

15 Comments
2024/11/09
16:59 UTC

2

Need help with Postgres full text search

My models structure

class Product(models.Model):
   name = models.CharField()
   tagline = models.CharField()

class ProductTopic(models.Model):
   product = models.ForeignKey(
        Product,
        related_name = "product_topics",
        related_query_name = "product_topic",
    )
    topic = models.CharField()

My view

query = request.GET.get("q")
search_vectors = (
    SearchVector("name") +
    SearchVector("tagline") +
    SearchVector("product_topic__topic")
)
product_list = (
    Product.objects.annotate( search = search_vectors )
    .filter(search=query)
    .distinct('id')
)

I'm using Django 5.1.3 & Postgres 16, Psycopg v3, Python 3.12.

The queryset returns no products, in the following instances:

  • when the query term is "to do", if even though "to-do" word exists in the table.
  • when the query term is "photo", if even though "photography" word exists in the table.

Possible to achieve this with full text search?

Do I need to use Trigram similarity or django-watson ?

Anyone please help me ASAP.

--------------------------------------------------------------------------------------------------

Update: I've found the solution using Cursor AI (Claude 3.5 Sonnet)

First we need to activate the pg_trgm extension on PostgreSQL. We can install it using the TrigramExtension migration operation.

from django.contrib.postgres.operations import TrigramExtension
from django.db import migrations

class Migration(migrations.Migration):
    dependencies = [
        ('your_app_name', 'previous_migration'),
    ]
    operations = [TrigramExtension()]

Run migrate.

from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank, TrigramSimilarity
from django.db.models.functions import Greatest
from django.db.models import Q

# View

query = request.GET.get("q", "").strip()

# Handle hyphenated words
normalized_query = query.replace('-', ' ').replace('_', ' ')

# Create search vectors with weights
search_vectors = (
    SearchVector("name", weight='A') +
    SearchVector("tagline", weight='B') +
    SearchVector("product_topic__topic", weight='C')
)

# Create search query with different configurations
search_query = (
    SearchQuery(normalized_query, config='english') |
    SearchQuery(query, config='english')
)

# Combine full-text search with trigram similarity
product_list = (
    Product.objects.annotate(
        search=search_vectors,
        rank=SearchRank(search_vectors, search_query),
        name_similarity=TrigramSimilarity('name', query),
        tagline_similarity=TrigramSimilarity('tagline', query),
        topic_similarity=TrigramSimilarity('product_topic__topic', query),
        similarity=Greatest(
            'name_similarity',
            'tagline_similarity',
            'topic_similarity'
        )
    )
    .filter(
        Q(search=search_query) |  # Full-text search
        Q(similarity__gte=0.4) |  # Trigram similarity
        Q(name__icontains=query) |  # Basic contains
        Q(tagline__icontains=query) |
        Q(product_topic__topic__icontains=query)
    )
    .distinct('id')
    .order_by('id', '-rank', '-similarity')
)

Project demo: https://flockly.co/

4 Comments
2024/11/09
15:54 UTC

17

How to find a Django dev cofounder, ?

Hey , Everyone

I am very interested in starting several AI-related projects. LLMs APIs are amazing, and there are numerous B2C applications that can be developed, particularly in fashion or health.—specifically, I’m aiming to build 3 or 4 within a month. I have a background as a Flutter developer +Firebase, but I’m also quite skilled in Django and PostgreSQL. I would love to find a co-founder who shares my passion and is proficient in Django as well. Are there any communities where I can connect with fellow Django developers?
Share ideas, brainstorm ,build fast and monetize it a week?
Honestly, I always had this idea: why don't developers join together to build, monetize quickly, and share the profit?

39 Comments
2024/11/09
13:48 UTC

7

Project Idea, Is this worth doing?

hi, my name is Joel , I am a uk based software engineer.

I have been working on an idea, using JS and a REST API in Django. the general gist of it is that it is using the canvas and added in functionality to allow users to design a functional webpage where they can choose buttons and redirects make queries and send and receive data, and use stripe to sell subscriptions or products. Basic website stuff. the webapp would include this, but also a team dashboard and hub for people to collaborate and find people who would be interested in making these webpages for business purposes. I'm thinking of letting the custom webpages leverage google maps for increased utility. I also would like to add GPT assistance features for if people want to use them on there custom webpages

Is this all too much for one application? any feedback would be appreciated.

I'm also open to any interested to help me out on what's left of the project, I have no qualms sharing credit or anything thereafter

13 Comments
2024/11/09
02:48 UTC

5

I'd like your opinions on how to organize my template files. I've come up with a structure, haven't fully tried it yet. Let me know what you think.

So I've been working with django for a few months now,
and I've been thinking a lot about a good way of organizing my templates and projects.
This is just a thought and I plan to refactor a project or two to see if it meshes well with this,
but here's what I'm thinking: limiting every app's templates to strictly adhere to
the following folder structure.

components
    - [component_x_folder]
        - component_x.py
        - component_x.js
        - component_x.css
        - template_x.html
    ...
includes
    - [include_x_folder]
    - include_x.html
    ...
widgets
    - [widget_x_folder]
    - widget_x.html
    ...
layouts
    - sections
        - [section_x_folder]
        - section_x.html
        ...
    - partials
        - [x-partial_x_folder]
        - x-partial_x.html
        ...
    - _base.html
    ...
pages
    - [page_x_folder]
        - sections
            - ...
        - pages
            - ...
        - partials
            - ...
    - page_x.html

======================
EXPLAINING THE FOLDERS
======================

1. layouts
----------
  - Contains templates for defining app layouts, <link> tags, common styling, <script> tags, common state, etc.
  - Can only nest "sections" and "partials" folders.
  - Only one folder per app and only at the root of the app template folder.
2. pages
--------
  - Typically extends layouts to present the main content of the page.
  - Could also not extend any layouts at all.
  - Can only nest "sections", "partials", and other "pages" folders (which can also nest sections, partials, and pages, and so on and so forth).
    - About 2 levels of nesting should be the absolute maximum, otherwise, create another django app.
3. sections
-----------
  - Logical sections of pages so individual template files don't get too big.
  - Can either be inside "pages", "layouts", or "sections" folders.
  - Can only nest other "sections" folders.
4. includes
-----------
  - Contains simple templates that can be included using the "include" tag or custom inclusion tags.
  - Strictly for simple UI components that are used in multiple places.
  - There can only be one folder per app and it can only be inside the root folder for the app's templates.
5. components
-------------
  - Contains complex components built using django_components or tetra.
  - There can only be one folder per app and it can only be inside the root folder for the app's templates.
6. partials
-----------
  - Contains templates that are meant to be rendered through htmx requests.
  - Can only either be inside "pages" or "layouts" folders.
7. widgets
----------
  - Contains form widget templates.

*************
Any thoughts?
5 Comments
2024/11/08
23:19 UTC

3

Best way to generate a single page PDF using selected items from current page in MkDocs

Let's say i have a page in MkDocs that has a several paragraphs of text together with a checklist.

I now want the user to be able to click a button, and generate a PDF with just the checklist on it. I do not want the paragraphs of text to print, and I want to be able to control how the checklist looks on paper vs the screen (e.g. change font font size).

Is there a tool or plug-in that would be suitable for this type of use case?

Thank you!

3 Comments
2024/11/08
22:20 UTC

0

Django-Postgres Starter

I was recently playing with Claude AI and decided to build a python app that will create a new Django/Postgres project.

I have put it out on Github here: jhstephenson/django-postgres-starter

I am curious to see if anyone finds this useful, but also want to see how it could be expanded and improved.

Let me know any thoughts you might have.

2 Comments
2024/11/08
17:45 UTC

4

Can i deploy a small django app on the Free App Platform tier on DigitalOcean?

I've never used digitalocean, so i wanted to try it out with a small app before i commit

6 Comments
2024/11/08
16:14 UTC

1

I need help deploying my django app on directadmin control panel

I watched a tutorial on how to do it (yes, the only one on YouTube) and my god was it awful. Does anyone know how to do it or any resource that might help?

2 Comments
2024/11/08
16:04 UTC

0

social media like function in django

i create social media in django but each i time click like button it refresh the page and working

how work like button without refreshing the page

2 Comments
2024/11/08
15:11 UTC

15

Feature Friday: The querystring tag!

Today's Feature Friday is about {% querystring %}!

The new {% querystring %} template tag in Django 5.1 makes it easier to access and modify the query string in your Django templates, letting you work with links that use query parameters.

Previously, if you wanted to add or change a single value in the query string, you would need to write a lot of code:

{# Linebreaks added for readability, this should be one, long line. #}
<a href="?{% for key, values in request.GET.iterlists %}
  {% if key != "page" %}
    {% for value in values %}
      {{ key }}={{ value }}&amp;
    {% endfor %}
  {% endif %}
{% endfor %}page={{ page.next_page_number }}">Next page</a>

With {% querystring %} you can replace all of that with this single line:

<a href="{% querystring page=page.next_page_number %}">Next page</a>

The {% querystring %} tag is particularly useful for things like filters and pagination—where you want to pass through most of the query parameters but modify one or two. You can add, remove, and modify query params, all from a single place!

Read more in the docs here: https://docs.djangoproject.com/en/5.1/ref/templates/builtins/#std-templatetag-querystring

9 Comments
2024/11/08
14:13 UTC

30

🎉 Introducing dj-data-generator! 🎉

We’re thrilled to announce the release of dj-data-generator, a new tool designed to simplify generating customizable test data for Django projects. Whether you’re setting up demo environments, populating databases for testing, or running performance tests, dj-data-generator offers efficient, built-in support to meet your needs—all without third-party packages.

Key Features:

- Generate any number of records for your project models and save them directly to the database with a simple django command

- Easy customization for model fields

- Handles unique and related fields

Check it out, and let us know what you think! Feedback, contributions, and suggestions are welcome as we continue to build.

📥 Check it out on PyPI:

https://pypi.org/project/dj-data-generator/

💻 Source Code and Docs on GitHub:

https://github.com/Lazarus-org/dj-data-generator

6 Comments
2024/11/08
14:04 UTC

0

Please help with hosting django in hostinger !

I bought the vps in hostinger, they have like ubuntu with openLiteSpeed and django, i also bought a domain but i dont know what to do now.

I cloned my github repo and im so confused. Hate to see theres no good tutorials how these things work.

Thanks.

13 Comments
2024/11/08
13:34 UTC

9

Choosing a Backend Framework for ML Prediction and Matching

Hey, if you’re going with some ML for prediction and matching—nothing very complicated—and implementing it in a web app, what sort of backend framework should I use, and what workflow should I implement? Usually, I’ve worked with Express.js.

1 Comment
2024/11/08
08:34 UTC

0

I would like feedback

I am creating an application template for django and I would like to know your opinions, the only condition is that when making django-admin startapp --template=

The app must be created within the django project in a folder called Apps

I leave you the link: https://github.com/simuel/DjangoHexTemplate.git

2 Comments
2024/11/08
06:29 UTC

7

Oracle forms builder alternate

Hi All, My employer recently upgraded from Oracle 11g to 19c..there was a reporting module that was built out of Oracle 6i and now with the upgrade the reporting module is breaking as there is no compatible version of Oracle forms builder with 19c.

So we have been asked to find alternates.I am thinking of suggesting Django with html as the requirement mainly focuses on generating excel docs by querying the Oracle tables.they need an UI component just to trigger the Excel generation process.

Now am from completely java background and have very minimal knowledge in Django.But I did start leaning python and found the file operations are much more clean and minimal code in python when compared to java and hence thinking of suggesting python with Django for a quick turnaround.

Is this good suggestion or Is there anything else out there that am completely missing for this scenario?

Thanks In advance

8 Comments
2024/11/08
01:05 UTC

1

Help with Changing Natural Primary Key to Surrogate Key

Hey all,

I'm working on a Django project where I currently have a model with a natural key as the primary key. I want to replace it with a surrogate key (using Django’s default auto-generated primary key). However, I have a related model where the foreign key points to the current model. I'm wondering what the best approach would be to make this change smoothly.

example:

from django.db import models

class Product(models.Model):
    sku = models.CharField(max_length=20, primary_key=True)  # This is the natural key I want to replace
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)

class Order(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)  # Foreign key points to Product
    quantity = models.IntegerField()
    order_date = models.DateTimeField(auto_now_add=True)
3 Comments
2024/11/08
01:01 UTC

9

Python version

I'm getting back into Django after a few years on other frameworks and on here https://www.djangoproject.com/download/ they recommend using the latest version of Python. Given how new python 3.13 is - is 3.12 recommended as of now? I saw another post on here asking about a similar thing but I wanted to ask given that it is explicitly stated on the djangoproject website.

Thanks!

10 Comments
2024/11/07
23:35 UTC

Back To Top