Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Good resources to learn Django
I am beginner on my road to backend. I have already learnt python basics, html basics and a bit of algorithms and data structure. The problem arose when I tried to learn Django. I mean all the resources that I have found so far are like “do this, write that and it will work”. Before I use something I would like to know why it works and how it works so that in theory I’d be able to do all the stuff even without Django or any other framework. Any good books or other online resources on Django you could suggest? I’d really appreciate. Thank you. -
Djano 3.2 is not generating permissions for model with pre-existing table
Under django 3.2, py3.7, followed pretty much standard steps to add a new model to the application but it does not appear in the permissions list under django-admin->groups. I had a pre-existing table in the DB called 'feedback'. Created a model for it under model.py. Under admin.py, created a ModelAdmin for it and registered it: admin.site.register(Feedback, FeedbackModelAdmin) Then executed python manage.py makemigration that created a migrations file with the respective migrations.CreateModel block for feedback model. Finally executed python manage.py migrate which ran the migration. Did not report with messages like, table already exists etc. The new model is visible in admin, data can be viewed and edited but no permissions were created for it ie When I go to the groups (as superuser), the available permissions list doesnt have this model. Have I missed a step? Is there another way to create permissions for this model other than running python manage.py migrate? -
Django admin screen won't let me see the list of entries under each mondel
I'm currently using Django and I just ran into this problem. When I click on a model in admin, it takes me back to the same screen. For example, if I click on news under NFL on this screen: It takes me to this screen instead of the list of entries: Why would this be happening? I haven't changed in the models since this occurred. -
How do you add an object to a many-to-many relationship through a form on Django?
I have the following models: class Exercise(models.Model): exercise = models.CharField(max_length=166) series = models.CharField(max_length=2) reps = models.CharField(max_length=2) station = models.ForeignKey(Station) class Workout(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE) day = models.CharField(max_length=1) exercises = models.ManyToManyField(Exercise) I want to be able to have a page where each Workout is displayed and the user can add Exercises when clicking a + button. So, this would take the Workout ID from the URL, and when creating an Exercise would automatically associate it to that workout. I was trying something along this line, but I don't think works: if request.method == 'POST': np_form = NewWorkout(request.POST) ne_form = NovoExercise(request.POST) if ne_form.is_valid() and np_form.is_valid(): nesave = ne_form.save() npsave = np_form.save(commit = False) npsave.exercises = nesave npsave.save() -
Field Boolean is not updating with time
I am building a Blog App And I am trying to hide blog posts which are older than seven days so, I am showing blog posts which are newer than 7 days. Then i think i can update the boolean if post is older then 7 days. I made a function in models to update the field after seven days. BUT The field is not updating. models.py import datetime from django.utils import timezone from datetime import timedelta class BlogPosts(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) is_older = models.BooleanField(default=False) title = models.CharField(max_length=30) date_added = models.DateTimeField(auto_now_add=True) def active(self): now = timezone.now() # changed 15 seconds for testing if date_added > timezone.now() - timedelta(seconds=15): is_older = False When someone posts a blogposts then boolean is saving to true and I am trying to set to False after 7 days. Any help would be much Appreciated. Thank You in Advance. -
Django: Pass context into a template using Ajax
I know this questionhas been asked here. But the anwser didnt quite fit my need. In my Django project I want to give context data as a dictionary to my templates. like in the normal: return render(request, 'the.html', context) I first build my entire Website without any ajax, so it would be quite a lot of work to entirely rewrite with the ajax HTML on succes like: $("#div_to_update").html( -- completely rewrite already written html code to fit the new ajax -- ) Is there a way to more easily pass context to django template like? $("#div_to_update").set_context(context_the_server_passed_to_ajax) -
How to authenticate a django app with docker from another django app with docker that takes care of users?
I have a django (Docker) container to login, register, etc. with django-simplejwt and another django container that I want to authenticate with the first one. I am using redis to cache the access and refresh token, but I don't know how to authenticate the second with the credentials of the first. Can anyone help? -
Django cache_page - prepopulate/pre-cache
I have one DB query that takes a couple of seconds in production. I have also a DRF ViewSet action that returns this query. I'm already caching this action using cache_page. @method_decorator(cache_page(settings.DEFAULT_CACHE_TIMEOUT)) @action(detail=False) def home(self, request) -> Response: articles = Article.objects.home() return Response(serializers.ArticleListSerializer(articles, many=True).data, headers={'Access-Control-Allow-Origin': '*'}) The problem is that after 15 minutes, at least one user needs to wait 15 seconds for the response. I want to pre-cache this every 5 minutes in background so that no user will need to wait. I use the default caching mechanism. My idea is to create a management command that will be executed using crontab. Every 5 minutes it will call the Article.objects.home() or the ViewSet.action and change it's value in the cache. As this is only one entry, I don't hesitate to use database caching. How would you do that? EDIT: as the default LocMemCache is single-threaded, I'll go with the database caching. I just don't know how to manually cache the view or QuerySet. -
OneToOne field in django default
Please help. I have a model: class Book(core.BaseModel): book_link = models.OneToOneField('self', default = "", on_delete=models.CASCADE) book_name = models.CharField('Name', max_length=250) I want to set 'self' in field book_link that will return in this field - book_name or Book Model object. But when I create new Book object - Django shows me in column "book_link" all book names which I can choose and save new object. I want that when I created new object it will authomatically save for this object this name! -
Count how many posts a user liked in Django
I would like to create a variable that I can pass through as context which will count how many posts a user liked. Here is my models.py class post(models.Model): title = models.CharField(max_length = 255) title_tag=models.CharField(max_length=255) author = models.ForeignKey(User, on_delete = models.CASCADE) body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=255, default = "coding") likes = models.ManyToManyField(User, related_name='blog_posts') def __str__(self): return self.title + ' | ' + str(self.author) + ' | ' + str(self.category) def get_absolute_url(self): from django.urls import reverse return reverse('article-detail',args=[self.id] ) def total_likes(self): return self.likes.count() Here is my views.py class ArticleDetailView(DetailView): model = post template_name = 'article_details.html' def get_context_data(self,*args,**kwargs): cat_menu = Category.objects.all() #amount_of_user_likes = ???? context = super(ArticleDetailView,self).get_context_data(*args,**kwargs) '''context allows us to access these values on our page''' stuff=get_object_or_404(post,id=self.kwargs['pk']) total_likes= stuff.total_likes() liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context['cat_menu'] = cat_menu context['total_likes']=total_likes context['liked'] = liked context['amount_of_user_likes']=amount_of_user_likes return context I am not sure how to query the Database in order to get the amount of posts that a user liked since the liked column is on the post table and not on the user table. However, since it is a many to many relationship then we can access the user somehow but I am unsure. -
psql not found in script for trying to control startup and shutdown order in Docker Compose
I'm trying to make sure my Django app waits for my Postgres db to start so I don't get this error django.db.utils.OperationalError: FATAL: the database system is starting up, I've read this https://docs.docker.com/compose/startup-order/, and here is what I have so far docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s timeout: 5s retries: 5 environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} backend: build: ./backend command: python3 manage.py runserver volumes: - ./backend:/code ports: - "8000:8000" command: ["./wait-for-it.sh", "db", "bash", "entrypoint.sh"] depends_on: - db wait-for-it.sh #!/bin/sh # wait-for-it.sh set -e host="$1" shift cmd="$@" # postgres until PGPASSWORD=$DB_PASSWORD psql -h "$host" -U "postgres" -c '\q'; do >&2 echo "Postgres is unavailable - sleeping" sleep 1 done >&2 echo "Postgres is up - executing command" exec $cmd Dockerfile # syntax=docker/dockerfile:1 FROM python:3.9.6-alpine3.14 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN \ apk add --no-cache postgresql-libs && \ apk add --no-cache --virtual .build-deps gcc musl-dev postgresql-dev && \ python3 -m pip install -r requirements.txt --no-cache-dir && \ apk --purge del .build-deps COPY . /code/ RUN chmod u+x ./wait-for-it.sh -
How to upload images to django REST api?
I'm creating a backend with DRF to upload json data that I later consume with a REACT frontend. By now it's pretty standard and simple. My django model has an ImageField that is serialized as a string in the form of "http://127.0.0.1:8000/media/example-randomcharacters.png". (I define the media folder in the settings.py in django). As expected, there is now a new file in the media folder with the name shown in the API, but when I try to get the image from the url it returns this: Of course it can't be used by react or any other external tool since the url doesn't provide the image. What am I doing wrong? Here is the django code: models.py: from django.db import models class Project(models.Model): """Programming related project to show on my website. """ title = models.CharField(max_length=100) description = models.TextField() cover = models.ImageField() link = models.URLField() date_started = models.DateField(auto_now_add=True) last_edited = models.DateField(auto_now=True) def _str_(self): return self.title serializers.py: from rest_framework import serializers from .models import Project class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' -
How to implement complex validation logic for models?
I'm trying to implement a simple REST API for a geocaching app. each geocache has several stations once a geocache instance is created you should be able to append stations the stations of a geocache have a fixed order (implemented through position) if a new station gets inserted at a specific position, all subsequent stations should be shifted an operation like 4. should set the geocache flag released to False (not released geocaches should not be shown to the user) a geocache can only be released if there exists at least one station If have the following model. models.py class Geocache(models.Model): title = models.CharField(max_length=70) released = models.BooleanField(default=False) class Station(models.Model): class Meta: unique_together = (('geocache', 'position'),) ordering = ['geocache', 'position'] geocache = models.ForeignKey(Geocache, related_name='stations', on_delete=models.CASCADE) position = models.IntegerField() title = models.CharField(max_length=70) instruction = models.TextField() There are two cases I need to validate: Is the position of the new station in the range from 1 to ([highest position] + 1)? When a geocache gets updated and released = True, is there at least one station for that geocache? I having trouble where to put those validation checks. I am aware of three potential possibilities: Model-level validation (through clean-methods) what is no longer … -
Two-tier menu: shall I make a raw SQL query?
Django 3.2.6 class Menu(NameUniqueMixin, ArchivedMixin, models.Model): TYPE_CHOICES = [ (MenuTypes.TOP.value, MenuTypes.TOP.value), ] type = models.CharField(max_length=10, choices=TYPE_CHOICES) class MenuLevelOne(NameUniqueMixin, ArchivedMixin, models.Model): menu = models.ForeignKey(Menu, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ) html = models.TextField(default="", blank=False, null=False) rank = models.PositiveIntegerField(default=0, null=False, unique=True, db_index=True, ) class MenuLevelTwo(NameUniqueMixin, ArchivedMixin, models.Model): level_one = models.ForeignKey(MenuLevelOne, on_delete=models.PROTECT, related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ) html = models.TextField(default="", blank=False, null=False) rank = models.PositiveIntegerField(default=0, null=False, db_index=True, ) I'd like to make a tree-like menu. Like this: os \windows \linux hardware \motherboards \sound cards We can see here a two-tier menu. I can't imagine what is the best way to select data from the database. Of course, I am going to use a template as well. I'm going to make several queries to the database, then use a loop. And cache this all in the template. In other words: I'm planning to organize an owfully inefficient piece of code here and conceal it using cache. Or I'm also thinking of a custom SQL-query, which I don't like at all. Could you tell me what is the bast way to select data from the database in this case? And how a rough draft of template for this meny may look like? -
Delay saving a Django ImageField until after the object has a pk
I have a Django model for a Book which has a slug field that's a hash based on its pk. It also has a thumbnail which is saved to a path including that slug. In Admin, if I create and save the Book without a thumbnail, and then add the thumbnail and save the Book again, this works: the thumbnail is saved to /media/books/<slug>/foo.jpg. BUT if I create the Book with a thumbnail image, and save it, the thumbnail is saved before the slug can be generated, so it's saved to /media/books/foo.jpg. This because files are saved before the model. I'd like to always include slug in the thumbnail's path, but I can't work out how to delay saving the thumbnail until after the slug has been generated. Any ideas? from django.db import models from hashes import Hashids def upload_path(instance, filename): return "/".join([books, instance.slug, filename]) class Book(models.Model): title = models.CharField(null=False, blank=False, max_length=255) slug = models.SlugField(max_length=10, null=False, blank=True) thumbnail = models.ImageField( upload_to=upload_path, null=False, blank=True, default="" ) def save(self, *args, **kwargs): super().save(*args, **kwargs) if not self.slug: # Now we have a pk, generate a slug if it doesn't have one. hashids = Hashids(salt="my salt", min_length=5) self.slug = hashids.encode(self.pk) kwargs["force_insert"] = False self.save(*args, … -
Passing function arguments into django model instance
I have a function that saves model to database based on dictionary of items provided. def bulk_creator_product_segment(df_records): """ Create object in Product segment model Saves objects in bulk based on unique constraint """ model_instances = [models.Product_segment( name=record["SegmentName"], product_category=models.Product_category.objects.get(name=record["CategoryName"]), ) for record in df_records] models.Product_segment.objects.bulk_create(model_instances, ignore_conflicts=True) Now I am trying to make it reusable and move things that change to function arguments. However I am having a problem with converting the name and product_category which are model field into function argument, which would mean something like this: bulk_creator_product_segment(df_records, firstfield, secondfield): model_instances = [models.Product_segment( firstfield=record["SegmentName"], secondfield=models.Product_category.objects.get(name=record["CategoryName"]), ) for record in df_records] It will not read firstfield as argument but as field names in the Product_segment which is wrong. -
How to show data from django models whose boolean field is true?
verified = models.BooleanField(default=False) I want to show only that objects in frontend whose verified field is true in django models -
How to get data through an intermediate table?
There are three tables. class CustomUser(AbstractUser): phone_number = models.CharField(unique=True, max_length=10, null=True, blank=True) class SGroup(models.Model): id = models.BigAutoField(primary_key=True) group_name = models.CharField(max_length=25) password = models.CharField(max_length=25) class GroupUser(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) group = models.ForeignKey(NoteGroup, on_delete=models.CASCADE) color = models.CharField(max_length=6) As you can see it's classic many-to-many sql relationship (can't use django's one, cause need additional fields like 'color'). I need to get certain user's all SGroups (then to pass them to creation form of other instance). How can I achieve that? -
can not login in production /django
I successfully deployed my django webapp but now I am unable to login as superuser even if I put correct credentials Screenshot -
Django wsgi subprocess.Popen processes die on gunicorn restart
I'm currently working on the django project served by Nginx+gunicorn. One of the features of the application is to run and stop bots in the background. I have achieved it using the subprocess python module, but the problem is the process I start with the subprocess.Popen becomes a child process of the gunicorn and dies so far I restart the gunicorn. The code looks like this: subprocess.Popen( ['runbot'], close_fds=True, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) Where 'runbot' is a executable of the bot which is up and running until it receives the SIGTERM signal. The options close_fds and start_new_session do not help here and the process still starts as a child of the parent gunicorn process. Interesting observation - it seems to be it is a wsgi-related issue, since everything is working as expected when I start the project with the builtin django dev web-server. How can I use the subprocess.Popen with gunicorn and run the process completely detached on the linux system? Other options I consider are Start using Celery (but I'm not sure if it is suitable for startng/stopping daemons) Make use of systemctl --user, but there was a problem that user systemctl services die after user logs out from … -
why give this error message when creating migration to myapp(Django website)
Unhandled exception in thread started by .wrapper at 0x0446E7C8> Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise exception[1] File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management__init_.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "F:\python_project\05project\mywebsite\videorequest\models.py", line 4, in class Video(models.model): AttributeError: module 'django.db.models' has no attribute 'model' -
How can I Subtract Total Monthly Income from Total Monthly Expenditure to get Net Income using Python Django for loop and list index
I want to display Total Monthly Income, Total Monthly Expenditure and Net Income in Django template using a table. The idea is that; as the user continue to add Income and Expenditure on daily basis, the script should be able to add all the income for every month of the year and do the same thing on expenditure too. And Subtract the Total Monthly Expenditure from the Total Monthly Income to get the Net Income for every Month of every year inside the Models. The result of the calculation should be displayed accordingly in Django Template (E.g. Month = July 2021 - Total Monthly Income= 48,900, Total Monthly Expenditure= 9,500, Net Income=41,450). The problem here is that once there is no expenditure amount in the Expenditure Model, no result is displayed in the Django Template table even though there are many income figures in the Income Model, and whenever there are expenditure figures in the Expenditure Model, the Total Monthly Expenses switches to other Total Monthly Income, thereby giving a wrong Net Income. For example, if there are three months for different years, the Total Monthly Income results (First Column) are displayed correctly but the Total Monthly Expenditure (Second Column) … -
modelformset to display forms according to ModelChoiceField in django
I am first time implementing the django modelformsets. I have a ModelChoiceField with 4 choices - c1, c2, c3, c4 in a ModelForm MF. MF has 3 fields F1, F2 and F3, where F1 is the ModelChoiceField. And MF is used to create the modelformset. I want to display as many forms as the choices available in F1 using modelformset, in this case - 4 forms, one for each choice. And only that choice need to be available for selection in the ModelChoiceField. Rest choices are hidden. Is there any way I can achieve this? -
I want a left outer join of three tables
I want to do a 'Left outer join' based on 'PMP_MODEL' as shown in the SQL query below. SELECT A.PMP_MANU_NUM, A.PMP_MODEL_NM, A.PMP_TYPE, A.BORE, A.HEAD, A.CAPACITY ,B.VISIT_DATE, B.VISIT_ENGINEER_NM, B.VISIT_ENGINEER_PHONE, B.REPAIR_CONTENTS ,C.SITE_NUM, C.SITE_NM, C.SITE_ADDR ,D.MANU_COMP_NM, D.MANU_COMP_PHONE, D.DELI_COMP_NM, D.DELI_COMP_PHONE, D.MANU_DT, D.FREE_SRV_ST_DT, D.FREE_SRV_END_DT, D.PAID_SRV_COMP_NM, D.PAID_SRV_COMP_PHONE FROM PMP_MODEL A LEFT OUTER JOIN PMP_REPAIR_HISTORY B ON A.PMP_MANU_NUM = B.PMP_MANU_NUM LEFT OUTER JOIN SITE_INFO C ON A.PMP_MANU_NUM = C.PMP_MANU_NUM LEFT OUTER JOIN SITE_DETAIL_INFO D ON A.PMP_MANU_NUM = D.PMP_MANU_NUM WHERE A.PMP_MANU_NUM = ? ; I tried with 'select_related', but it doesn't work. class PmpModelList(APIView): def get(self, request, format = None): pmpList = PmpModel.objects.select_related('pmp_manu_num') serialize = PmpModelSerializer(pmpList, many = True) return Response(serialize.data) -
DRF : Custom child serializer to add a field from the parent
In my current model I have JSON field called "data", previously "foo" and "bar" fields was inside the JSON field. For performance reasons I had to externalize foo and bar to dedicated fields with a django migration. but i would like to keep the same endpoint format when reaching the API. Which means put "foo" and "bar" in the class DataSerializer(serializers.Serializer) How is it possible to share the data from FooModelSerializer() to the DataSerializer() ? endpoint output format: "results": [ { "id": 1 "data": { "json_field_A": "charValue", "json_field_B": 123, "json_field_C": "charValue", "foo": 12, "bar": "barValue" }, "other": 12345 }, { "id": 2 "data": { "json_field_A": "charValue", "json_field_B": 123, "json_field_C": "charValue", "foo": 12, "bar": "barValue" }, "other": 12345 } ] model : class FooModel(models.Model): data = models.JSONField( blank=False, null=False, default=some_default ) foo = models.IntegerField() bar = models.CharField() other = models.IntegerField() serializer : class DataSerializer(serializers.Serializer): json_field_A = fields.CharField() json_field_B = fields.IntegerField() json_field_C = fields.CharField() class FooModelSerializer(serializers.ModelSerializer): data = DataSerializer() class Meta: model = models.FooModel fields = ['id', 'data', 'other', 'foo', 'bar']