/r/django
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
I'm picking Django up after a long time away. I'm struggling with something which i feel is probably really basic, so apologies if you clicked this thread looking for a really tricky puzzle to solve.
my models.
#coaches/models.py
class Coach(models.Model):
club = models.ForeignKey(Club, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
email = models.EmailField(unique=True)
phone = models.CharField(max_length=20)
teams/models.py
class Team(models.Model):
name = models.CharField(max_length=200)
club = models.ForeignKey('clubs.Club', on_delete=models.CASCADE)
coaches = models.ManyToManyField(Coach, related_name='teams')
players = models.ManyToManyField(Player, related_name='teams')
This is the view in code.
def team(request):
"""
present the user with a list of teams to choose from
based on their username appearing in the data.yaml file
"""
context = {}
coach = Coach.objects.get(email=request.session["username"])
print(f"Coach: {coach}")
teams = Team.objects.filter(coaches=coach)
print(f"teams: {teams}")
context["teams"] = teams
return render(request, 'coaches/team.html', context)
I've tried this in code and in the shell. this is the output i get.
Coach: Marcelo Bielse
teams: <QuerySet []>
So i correctly populate the coach, but can't pull back the teams the coach is aligned with. ive checked the admin and the coach is definitely attached to the Team. But I always get the empty query set. I wonder if there isnt some 180 degree issue in my thinking that i should be calling for all teams with the specific coach? Is that the area? What have i missed?
Hey,
Repository url: https://github.com/adinhodovic/django-mixin
I've built a monitoring-mixin for Django-prometheus. A monitoring mixin is a set of Grafana dashboards and Prometheus rules written in Jsonnet. There are several others such as https://github.com/kubernetes-monitoring/kubernetes-mixin so I thought of writing one for Django.
I also have a blog post on this topic: https://hodovi.cc/blog/django-monitoring-with-prometheus-and-grafana/.
There's also dashboard preview images in the repository. Looking for any input to hopefully standardize Grafana dashboards and Prometheus alerts for Django over time!
Maybe useful for some! Thanks for taking a look.
Hi all,
I am working on a simple Django app for monitoring the progress of Snakemake workflows. For context, Snakemake is a workflow manager, largely targeted towards life sciences (bioinformatics, genomics, etc). It is run on the command line and currently lacks a good way to monitor the progress of your workflows (they can run for weeks in some cases).
I have experience building Django webapps and deploying them for myself. However with this, I would like to make the whole webapp a pip installable package such that users can just install via pip and spin up the server. This is extremely important, as in order for this to be a useful tool, the barrier to entry should be very low for users with little technical experience.
I have already worked out how the workflows will communicate with the running Django server. My general idea is this:
Where I have questions is how to handle deployment and migrations:
Appreciate any thoughts on this! Happy to answer any questions that would help clarify.
Hi everyone,
I started testing OpenAI's new assistants API, which can automatically vectorize , and search in your uploaded files.
I tried it out, and although it's painfully slow at the moment, it's also working flawlessly.
Response times can vary from 3 to 10 seconds which is awful, but for me it's OK since this will only be used internally.
Now, i've been running my django app with gunicorn using WSGI, so every view , every API endpoint is sync.
I have 0 experience when it comes to async, but with some examples written by OpenAI themselves i created an async version of this API.
The whole app runs on a small VPS with 2 vCPU but i don't want to accidently block the whole app with a few users calling this endpoint at the same time.
Is anyone using Django with 99% sync views and 1% async?
Is it a good idea to mix and match? Should i try to handle this with my celery workers?
It seems to me that there's no perfect way to use MongoDB in django. I mean as the user model and all. It seems like everything breaks and I have to rewrite a lot of functionalities and then more things break. I'd have been lost with AI. I would like to know if there's are resources that actually document how to go about connect django fully with mongo. Thank you.
I had 2 models and I decided to move one of them into a new app. Now whenever I call makemigrations I get the error "original_app.models.MODELNAME doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.".
The original app is in installed apps. Any help with this issue?
Hey Django devs! 👋
I'm excited to share Leverans, a deployment tool I've been working on that makes getting your apps online stupid simple. Here's why you might love it:
🚀 Key Features:
Why I built this: Deploying apps is a pain. Existing tools are either too complex or too restrictive. Leverans fixes that.
For example, this is all you need to describe a simple Django project:
```yaml
project: django
apps:
main:
domain: your-domain.com
port: 8000
volumes:
django-sqlite: /data
```
And run the `lev deploy` command. And that's it, your application is online. On your own private VPS server.
Docs: https://leverans.dev
GitHub Examples: https://github.com/ethanhamilthon/leverans/tree/main/examples
This is v0.2.0 - our first stable release. Would love your feedback and a ⭐ on GitHub if you find it useful!
For the past few months, I’ve been working on a web app—a Reddit clone—using Django for the backend and React for the frontend. The app focuses on stock market tickers, allowing users to post and discuss specific securities, similar to how Reddit functions.
This is my first time building something like this, and I don’t have a background in computer science. Now, I’m ready to take the next step and deploy my app, but I have no idea where to start.
I’ve heard about AWS, Azure, and other hosting platforms, but I’m not sure which one would be best for a beginner like me. I’d really appreciate any guidance, resources, or tutorials (e.g., YouTube videos, step-by-step guides) that can help me with deployment.
Thanks in advance for your help!
Dear Django community,
I am using the modern standard of Django + HTMX + Crispy. As part of a form, I would like the user to select one of 10'000 clients. The user should type in a few letters of either the first name or the last name and then get a dropdown of matching clients and be able to click on one of them.
So far, I explored and considered the following options:
I could build it from scratch in pure HTMX. Would work, but it's work traveling back and forth, doesn't seemingly integrate with the rest of my form and I'd need to travel to the backend for each letter the user types.
I could pass the entire client list to the frontend and do in Javascript, but I don't like to code stuff in javascript.
I implemented this video: django-crispy-forms & ModelChoiceFields / Select2 Integration for Searchable Form Fields, which does it as a standard Django field and then puts Select2 over it. However, the page load is too slow and I don't like the dependency on jquery.
I considered django-autocomplete-light, however, at first sight, it seems quite heavy with dependencies on multiple libraries. Further it requires me to have a dedicated Class based view and complex statements in the Form that appear to contain a fair amount of magic.
Thanks for your advice and proposed other solutions. I guess all of my options would work, but I am looking for a lean best practice of doing these kinda things in modern times.
django-hstore-widget
is a widget that simplifies HStoreField
usage from admin panel.
Changes since last post:
Please take a look at the github repo or give a ⭐
I write code for Django but without a local runtime for it, because I run it on a docker container.
All the guides I have seen about django-stubs or django-types say you have to pip install
them. I guess you are meant to pip install
them into the virtual environment you run the project with, and also tell your Python LSP which virtual env to use for the current project.
How can I make my LSP (basedpyright I guess, but I will happily switch if I can have a better experience) aware of django typings, but without having a local runtime for the project?
Hi everyone, I am a bit confused as to why ORM behaves this way. Suppose I have models One and Two, and model Two has a Foreign key to One. The code below works fine
one = Model_One()
two = Model_Two(model_one=one)
one.save()
two.save()
This works because we save one before two and no data is lost. two is allowed to be saved because one by that point would have an id in the DB. Cool. Now what if those two models were related by Generic Foreign Key?
one = Model_One()
two = Model_Two(content_object=one)
one.save()
two.save()
Now this one does not work! Two complains that it's content_id is null. I went in the debugger. When models are instantiated, everything is at it should be, two has a field content_object that references one. But as soon as one is saved, for whatever reason two loses its reference to one, the field content_object is empty! Is this intended behavior? When I run the code below, everything is good, nothing gets lost.
one = Model_One()
one.save()
two = Model_Two(content_object=one)
two.save()
This is weird to me, because in this regard it is intuitive the GFK would work the same as FK. I would really appreciate if anyone could explain this moment to me. Maybe this is a bug?
I've been exploring REST frameworks like Django REST Framework (DRF) and Django Ninja, and I noticed that they both introduce their own layers for authentication.
This creates separate libraries, like djangorestframework-simplejwt
for DRF and django-ninja-simplejwt
for Django Ninja.
But Django already has a good auth system with backends that work for all views. Why don’t these frameworks just use Django’s auth backends and a middleware?
Is Django’s auth system missing something, or do these frameworks need extra features that Django doesn’t provide?
Hi guys, I'm looking to contribute to open source. I'm aiming for GSOC 25. I graduated this year and am currently working as an SDE. I'm looking to contribute to Python or Django organizations. Can someone please suggest a beginner-friendly repository that could help me get into GSOC 25, given 3-4 months of time?
I see that they have templatized basic html elements and it's hard to style them now.
This gave me a headache:
Any tips will be appreciated.
Hi Folks, I have tests for a view, when run don't trigger the logger.info() statements within the view's code.
But same view when triggered manually (for ex: via postman) shows up logs in the console generated by the logger.info() statements.
Is there something I am missing to be able to see logs generated during tests?
Hey y'all.
I have a Django project that allows users and admins to upload files to be stored in the /media directory. This works great in my local project folder, but since I'm going to have to migrate to Docker and use a VPS soon, I figured that I should test everything out with a local bucket first.
import boto3
from botocore.exceptions import NoCredentialsError, ClientError
def test_s3_connection():
s3 = boto3.client(
's3',
endpoint_url='http://localhost:9000',
aws_access_key_id='minioadmin',
aws_secret_access_key='minioadmin',
)
try:
response = s3.list_buckets()
print("Buckets:")
for bucket in response['Buckets']:
print(f" - {bucket['Name']}")
except NoCredentialsError:
print("Credentials not available.")
except ClientError as e:
print(f"ClientError: {e}")
if __name__ == "__main__":
test_s3_connection()
I can successfully see my bucket using this testing script.
This is how I tried adding it as a storage backend:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'portal',
'storages',
]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_ACCESS_KEY_ID = 'minioadmin'
AWS_SECRET_ACCESS_KEY = 'minioadmin'
AWS_STORAGE_BUCKET_NAME = 'ncjfa'
AWS_S3_ENDPOINT_URL = 'http://localhost:9000'
AWS_S3_SIGNATURE_VERSION = 's3v4'
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
And here is how I've been uploading these files with a path:
def admin_static_file_upload_to(instance, filename):
return os.path.join(
'admin_events',
instance.folder.name,
filename
)
class AdminStaticFile(models.Model):
folder = models.ForeignKey(AdminStaticFolder, related_name='files', on_delete=models.CASCADE)
name = models.CharField(max_length=255)
file = models.FileField(upload_to=admin_static_file_upload_to)
uploaded_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
An admin can upload files using the built-in admin console.
Somehow, my files are appearing in the base directory of my project folder. Not even /media, like before.
What am I doing wrong? Thanks for the help!
My website is loading slowly, and I suspect the performance hit is due to unused CSS being loaded with every page. While I use frameworks like Bootstrap and custom admin styles, much of the CSS is not relevant for every page. I'm wondering if there's a way to remove unused CSS dynamically, specifically through middleware.
I’d like to know if it's possible to automatically purge unused CSS before serving the page, without permanently modifying the CSS files. The idea would be to handle this process on every request to ensure only the necessary CSS is sent to the browser, thus improving load times. Can anyone guide me on how to implement this in Django, or if there are best practices to handle CSS purging dynamically using middleware or a similar solution?
As of now, I have a VPS on hetzner (I had it on Digital Ocean previously, but I migrated to hetzner).
I use apache to host it, all media files and static files along with database are hosted on the same VPS, and I have a bunch of cron jobs to run some background jobs...
As of now, I make changes locally, and push them, then ssh into the VPS, pull the changes, check permissions for each directory, restart apache and all the hassle...
I've also used Digital Ocean's app platform, so when I push to github, it will redeploy the project, but then, I'd to host the database and media files seperately, otherwise they will be gone after the re-deployment. Plus background tasks are pain, and the costs getting higher and higher.
I am looking for similar solution, but maybe somewhere else and not on Digital Ocean. Please suggest me the easiest options, or tricks to do the same on a VPS.
I really need some help.
Thank you very much..
I am an individual who has always loved the films of Tarantino. I’ve watched all of them at least ten times each ( 01/1224) but I can confidently say that if Django isn’t your favourite then you are wrong ( simply it’s no matter of opinion) if you watch Django unchained, the first scene of Mandingo fighting portrays 7 reactions to a murder in 3 seconds that I personally think is more valuable to modern cinematography than the 30 years that proceeds it. Honestly! Watch the eye popping scene again and again and you’ll see that in 3 seconds we have 7 different societal beliefs emerge from one action. The beneficiary The bystander The “ life goes on” The “ it is what it is” The “ is this what I must tolerate?” The “this is what society made me do” The “ this is an injustice” All performed in 3 seconds
Hi everyone,
I want to contribute on some django projects. if any one are willing to suggest me some applications please feel free to reply to this post.
Thanks.
Hi, so whenever some error comes up during development, it's a pain to read through the logs because every text is white.
is there any way to enable syntax highlighting for the logs in the terminal ?.
I have attached a screenshot
Ive spent hours on this and I can not figure it out. So below is an example of the out put table. I'm trying to get rid of the trailing '-' after the weight numbers. So there are "weight_implements" tied to an "event" for data collection purposes. Some events may have several implements, but usually just one. I used regroup to only list same names one time for clarity. Somehow it keeps printing 'yoke' at the end and a trailing '-'. I can't seem to figure out as the nested loops have sufficiently melted my brain.
Weight Class | Sandbag Medley | Deadlift |
---|---|---|
U231 (Male) | Sandbag: 150 lbs - 200-lbs - 220 lbs - Yoke: 450 lbs - yoke: | Deadlift: 495 lbs - |
<tbody>
{% for weight_class in competition.allowed_weight_classes.all %}
{% for div_weight_class in division.divisionweightclass_set.all %}
{% if div_weight_class.weight_class == weight_class %} <tr>
<td>{{ weight_class.name }}
({{ div_weight_class.get_gender_display }})
</td>
{% for event_order in ordered_events %}
<td> <dl> {% for group in event_order.event.implements.all|group_implements %} {% if group.implements|length > 1 %} <dt>{{ group.name }}:</dt> <dd>
{% for implement in group.implements %}
{% if implement.division_weight_class == div_weight_class %}
{{ implement.weight }} {{ implement.get_weight_unit_display }}{% if not forloop.last %} -{% endif %} {% endif %} {% endfor %}
</dd> {% else %} {% for implement in group.implements %} {% if implement.division_weight_class == div_weight_class %} <dt>{{ group.name }}:</dt> <dd>{{ implement.weight }} {{ implement.get_weight_unit_display }}</dd> {% endif %} {% endfor %} {% endif %} {% endfor %} </dl> </td>
{% endfor %} </tr>
{% endif %} {% endfor %} {% endfor %}
</tbody> </table>
I am trying to launch my web app and I am very confused . I have very less budget because it a side project my web app is made on top of django help me with this.
What's on the horizon for Django performance? WebAssembly integration? Advanced caching technologies? Predictive loading techniques? Give us a glimpse into the future of web application optimization!
How do you protect your Django applications from traffic spikes? Custom middleware? Advanced rate-limiting techniques? Share your strategies for maintaining performance under heavy load.
Deep database optimization techniques! Custom indexing? Query plan analysis? PostgreSQL magic? Show us how you squeeze every millisecond of performance from your database layer.
For those running Django in microservices architectures: How do you maintain low latency across service boundaries? Efficient inter-service communication? Load balancing strategies? Spill the secrets!