Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get ImageField url when using QuerySet.values?
qs = self.items.values( ..., product_preview_image=F('product_option_value__product__preview_image'), ).annotate( item_count=Count('product_option_value'), total_amount=Sum('amount'), ) product_option_value__product__preview_image is an ImageField, and in the resulting QuerySet it looks like product_preview_images/photo_2022-12-10_21.38.55.jpeg. The problem is that url is a property, and I can't use media settings as images are stored in an S3-compatible storage. Is it possible to somehow encrich the resulting QuerySet with images URLs with a single additional query, not iterating over each one? -
LTM Load Balancer drops connection while App waiting for big SQL query response
Newly implemented LTM Load Balancer drops connection while our App is waiting for big SQL query response. Now i need to find some workaround because appearently extending timeouts on LB is not a way to go. App runs on Django and MSSQL Is there any possibility to lets say send query to DB -> get some kind of transaction ID (JWT?) -> close connection -> create GET with some transaction ID to check if there is result of this query? (Not sure how this transaction ID would be stored on DB side tho) Is Pagination doin something like this? I would like to avoid making this like this: Create API endpoint which runs queries to DB -> Send request to API -> DB process with query and put results in new table -> send query to new table -
504 Gateway Timeout (Gunicorn-Django-Nginx) Docker Compose Problem
There is one process backend which take around 1-2 minutes to process. The loading screen runs for 1 minute and shows 504 Gateway Timeout Here's the log in nginx.access.log 172.18.0.2 - - [16/Dec/2022:23:54:02 +0000] "POST /some_request HTTP/1.1" 499 0 "http://localhost/some_url" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" But from the django debug log, I can see that the POST request is still processing at the backend docker-compose.yml timeout is set to 300, without it, the browser will return 502 error (connection prematurely closed) services: web: image: genetic_ark_web:2.0.0 build: . command: bash -c "python manage.py collectstatic --noinput && gunicorn ga_core.wsgi:application --bind :8000 --timeout 300 --workers 2 --threads 4" This is all the params I have tried in nginx.conf but still the 504 timeout is returned after 60s server { # port to serve the site listen 80; # optional server_name server_name untitled_name; ... # request timed out -- default 60 client_body_timeout 300; client_header_timeout 300; # if client stop responding, free up memory -- default 60 send_timeout 300; # server will close connection after this time -- default 75 keepalive_timeout 300; location /url_pathway/ { proxy_pass http://ga; # header proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_connect_timeout 300s; proxy_send_timeout … -
Django Comments Xtd Comments are not nesting
I followed the tutorial on https://django-comments-xtd.readthedocs.io, everything seems to work find, the forms and the comments are working, but on the website they are not displayed properly. instead of looking like this: They all look like this The reply is not nesting under the comment but in the admin its working you can see how it nests take a look: Please help -
Is it an antipattern to use `request.POST or None` to initialize a Django form?
I came across a blog post arguing that the following is an antipattern: def some_view(request): form = MyForm(request.POST or None) # … Source: https://www.django-antipatterns.com/antipattern/using-request-post-or-none.html However, I'm not clear on the problems that using it could cause. I have used this to keep my views concise, without noticing any unexpected behavior. Is this an antipattern? If so, why? -
Error after migrating django database to postgresql
I have recently changed my database from sqlite3 in django to postgresql as I prepare my app for production. After making changes in settings.py, I have tried making migrations and I am getting an error. After running python manage.py migrate --run-syncdb I get the error below in the terminal System check identified some issues: WARNINGS: users.Document.uploaded_at: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now` users.Order.amount: (fields.W122) 'max_length' is ignored when used with IntegerField. HINT: Remove 'max_length' from field users.buyer.uploaded_at: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now` Operations to perform: Synchronize unmigrated apps: channels, chatapp, crispy_forms, messages, payments, staticfiles, users Apply all migrations: admin, auth, contenttypes, sessions Synchronizing apps without migrations: Creating tables... Creating table users_user Creating table users_document Creating table users_buyer Creating table users_category Creating table users_service Creating table users_profile Creating … -
Editing it in html when we pull data from Django
The news saved in the system will come to my page. I pulled data from django. Currently the data is coming one after the other. I want to pull 3 data side by side after it's will be 3 data below again and so it will go like that. How can i do this? My kategori.html: {% extends "homebase.html" %} {% block title %} {{ setting.title }} {% endblock %} {% block keywords %} {{ setting.keywords }} {% endblock %} {% block description %} {{ setting.description }} {% endblock %} {% block head %} <link rel="icon" type='image/png' href='{{ setting.icon.url }}'/> {% endblock %} {% block header %}{% include 'header.html'%}{% endblock %} {% block sidebar %}{% include "sidebar.html" %}{% endblock %} {% block content %} {% load static %} <section id="news" data-stellar-background-ratio="2.5"> <div class="container"> <div class="row"> <div class="col-md-12 col-sm-12"> <div class="section-title wow fadeInUp" data-wow-delay="0.1s"> <h2>TIBBİ BİRİMLER KATEGORİSİ</h2> </div> </div> <div class="col-md-4 col-sm-6" > <!-- NEWS THUMB --> <div class="news-thumb wow fadeInUp" data-wow-delay="0.4s"> {% for rs in category %} <a href="kategori.html"> <img src="{{rs.image.url}}" class="img-responsive" alt=""> </a> <div class="news-info"> <span>{{rs.create_at}}</span> <h3><a href="bos-sayfa.html">{{rs.title}}</a></h3> <p>{{rs.description}}</p> <div class="author"> <div class="author-info"> <p>{{rs.keywords}}</p> </div> </div> </div> {% endfor %} </div> </div> </div> </div> </section> {% endblock %} {% … -
Postgresql with heroku
I have a Postgres database on my PC with all data that I need so far in the project, my app is deployed on Heroku without any data in the database Heroku gave to me. I want to provide my app on Heroku with data from my DB. I tried using pg_dump but couldn't figure out what I was doing wrong, I thought I could host my DB and then somehow connect it. -
Filtering Django API by time not working before "10:00:00"
I made this Django API to search by date and time, the date filter works perfectly but once I start trying to filter by time it only filters data from 10:00:00 to 24:00:00 and completely disregards filtering anything stamped 00:00:00 to 09:59:59. Here's an example of the way I'm storing my data in my db: "id": 10, "added_date": "2022-12-16", "added_time": "10:12:54", "name": "Name", Here is my code: class Search(generics.GenericAPIView): def get_queryset(self): start_date= self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') start_time= self.request.query_params.get('start_time') end_time = self.request.query_params.get('end_time') try: search= objects.filter(added_date__range=[start_date, end_date], added_time__range=[start_time, end_time]) return search.all() except Exception as exception: return Response(response500('No Data Found', exception), status=status.HTTP_500_INTERNAL_SERVER_ERROR) def get(self, request): try: queryset = self.get_queryset() serializer = SearchSerializer(queryset, many=True) response = Response(serializer.data) return response except Exception as exception: return Response(response500('No Data Found', exception), status=status.HTTP_500_INTERNAL_SERVER_ERROR) I believe the "0" in front of times such as 09:30:00 is throwing off the search. However in the table 09:04:10 would show up as 9:4:10 and it still giving problems. Any help would be greatly appreciated, thank you! -
use *args in django url paramater
I have a webpage within my site which shows a list of Lego set themes. Each theme may have sub-themes and those sub-themes may also have sub themes. In the image below each indentation level represents what themes are sub-themes of other themes. For example on my page a user could take the path: http://127.0.0.1:8000/themes (shows all parent themes) http://127.0.0.1:8000/themes/train (shows all sub themes of train) http://127.0.0.1:8000/themes/train/9V (shows all sub themes of train/9V) http://127.0.0.1:8000/themes/train/9V/My%20Own%20Train (no sub themes) In my view i suppose i would use *theme to handle any number of sub-themes url path http://127.0.0.1:8000/theme/train/9V/ views.py def theme(request, *theme): #theme = ('train', '9V') theme_path = "".join([theme + "/" for theme in themes]) #theme = 'train/9V/' theme_items = db.get_theme_items(theme_path) sub_themes = db.get_sub_themes(theme_path) context = { "parent_theme":theme[0], "theme_items":theme_items, "sub_themes":sub_themes, } return render(request, "App/theme.html", context=context) urls.py urlpatterns = [ ... path('theme/<str:theme_path>', views.theme, name="theme"), ... ] theme.html sub_theme.0 = name of the sub theme e.g '9V' sub_theme.1 = image url header = parent to sub theme e.g 'train' {% for sub_theme in sub_themes %} <div class="theme-container"> <p><a href="{% url 'theme' parent_theme %}/{{sub_theme.0}}">{{sub_theme.0}}</a></p> <img src="{{sub_theme.1}}" alt="{{sub_theme.0}}_url"> </div> {% endfor %} How could i pass multiple parameters into the url which can be handled by my … -
Django & Digital Ocean: Exception("DATABASE_URL environment variable not defined") When running local server
I built a django app on my local machine, and then used this tutorial to deploy it with app platform (https://docs.digitalocean.com/tutorials/app-deploy-django-app/) The deployment was successful. However, now when I try to run my django app locally to continue development, I’m getting the following error: …/settings.py", line 95, in raise Exception(“DATABASE_URL environment variable not defined”) Exception: DATABASE_URL environment variable not defined Current settings in settings.py: DEVELOPMENT_MODE = os.getenv(“DEVELOPMENT_MODE”, “False”) == “True” DEBUG = os.getenv(“DEBUG”, “False”) == “True” I am unsure of how to reset my settings.py file so that it points to a local sqlite3 db for development. -
Static files not loading
I'm trying to create an homepage for my app but my page keeps loading after adding the STATIC_ROOT and STATICFILES_DIR. it gives Broken pipe from ('127.0.0.1', 49634) in my terminal. This is my home.html This is my settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') this is my urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to update FileField or ImageField hosted by s3 in my Django project?
I have a Django web app that allows users to upload a picture or video, and it works perfectly when I upload it the first time, but when I go back to change it, it doesnt update, it allows me to to clear the field but I can't upload a new file. I'm totally new to s3 and am having a hard time reading the docs. I'm not sure what code I should attach, but this is in my settings.py AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I can also share my views.py but I feel like it has something to do with permissions. Any help would be greatly appreciated! -
Django return a ManyToMany field from other class
I have two classes in django: class MovementsGyn(models.Model): gyn_name = models.CharField('Name', max_length=70) gyn_desc = models.TextField('Description', blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['id'] class Rod(models.Model): Rod_name = models.CharField('Rod Name', max_length=70) movements_gym = models.ManyToManyField(MovementsGyn) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['id'] And a view to show the result grouped: def estatistica(request): template = 'moviment.html' estatic_movem_gyn = Rod.objects.filter(owner=request.user) \ .values('movements_gym').order_by('movements_gym') \ .annotate(qtde=Count('id')) context = { 'estatic_movem_gyn' : estatic_movem_gyn } return render(request, template_name, context) The result is movements_gym grouped and, in qtde, the quantity of register that we have in database. The question is, how can I show the field gyn_name that are in MovementsGyn models ? -
Receiving Error: 'apxs' command appears not to be installed
This is the error I am receiving: RuntimeError: The 'apxs' command appears not to be installed or is not executable. Please check the list of prerequisites in the documentation for this package and install any missing Apache httpd server packages. How can I get around this? I have received this while trying to install different packages. I am working on a Django project. I have already made sure the apache2-dev package is installed. -
Why does request.POST always contains name of the button? How to avoid it?
This is my HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {% load static %} <script src="{% static 'jquery-3.6.2.min.js' %}" ></script> <script src="{% static 'jquery.js' %}" ></script> </head> <body> <form action="{% url 'index' %}" method="post"> {% csrf_token %} <button name="button1">button1</button> <button name="button2">button2</button> <input type="text" name="textbox"> </form> </body> </html> Every time I type some text in the textbox, let's say I type: "hi" and hit enter, the request.POST returns: <QueryDict: {'csrfmiddlewaretoken': ['FX1qFNzbQUX3fYzAwW27cOu83omLzifnlLU5X0WXXVdOiyNretM5b3VgsGy1OogA'], 'button1': [''], 'textbox': ['hi']}> Why does request.POST contain 'button1': [''] even though I haven't clicked on it? Is there a way to avoid request.POST to have 'button1': ['']? -
Use multiple workspaces containing django without PYTHONPATH
Sometimes I need to run our project with django backand in multiple workspaces on different git versions. While doing it I discovered that django is heavely relying on PYTHONPATH and probably because of that mixing up the workspaces. When I call python manger.py runserver for example, I can see sources being pulled from the other workspace. On contrary, if I remove both workspaces from PYTHONPATH (which was the only thing in there) the above command fails with the quite infamous error: File "/opt/homebrew/Cellar/python@3.11/3.11.0/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: XYZ For me it looks like, he can not find the modules outside django, which has been otherwise obtained from the PYTHONPATH path. Since all our modules including the one that is reported to be missing are on the same level as django I tried to extend the sys.path in manage.py like this: import pathlib def main(): current_dir = pathlib.Path().resolve() [sys.path.append(str(x)) for x in current_dir.parent.iterdir() if x.is_dir() and not x.name.startswith(".")] Although I can see the path being extended the above exception still occurs. Any help on … -
How to customize image toolbar in ckeditor and enable Upload outside admin panel?
The first problem: If click on the image toolbar, the wizard appears with additional settings. Can I modify it to upload the image in one click without entering additional information and sending the image to the server? The second problem: Outside the admin panel, there is no upload tab on the image toolbar. How to fix it? Thanks for your time. -
Django with DRF. Users cannot sign in with their credentials
I have a web app using Django as the backend and React as the frontend. I have a sign up form where the users enter their credentials and the profile is created in the database. However, when the users create their profile, they are unable to login even though the user data is available in the database. Altering the user password with the django-admin panel fixes this issue and the users can login sucessfully into their accounts. I'm assuming this is an issue with the password saving during profile creation but I can find the issue. Profile creation method # Create user @api_view(['POST']) def sign_up(req): serializer = UserSerializer(data=req.data) if serializer.is_valid(): if User.objects.filter(email=serializer.validated_data['email']).exists(): return Response({'email': 'The email entered is already in use by another account.'}) serializer.save() return Response({'status': 'success'}) else: return Response(serializer.errors) User sign in method # Sign in user @api_view(['POST']) def sign_in(req): username = req.data['username'] password = req.data['password'] user = authenticate(req, username=username, password=password) if user is not None: return Response({'status': 'success'}) else: return Response({'err': 'The username or password entered is incorrect.\nThe username and password are case sensitive.'}) I have tried forcefully resaving the password on profile creation but that doesn't work. Have also tried some online solutions but to no … -
How to pull information from html and use it in a view in Django
Im trying to send a post request with a payload that includes a username and password. The post request works fine on its own but I'm not sure how to get the user and pass that are entered and use them with the post request. Trying to take the data entered into the html and use it in a view I've looked around online and found something suggesting something similar to which doesn't fail but instead returns none: username = response.GET.get['username'] password = response.GET.get['password'] I see this stack overflow:Django request.POST.get() returns None that definitely has the correct answer in it but I don't quite understand whats going on/what I need to do in order to get the result im trying for. I can see its something to do with that I have to post the data to the url or something for it to be eligible to grab from the above statements or something, but again, I don't really understand whats happening. Honestly what im looking for here is an ELI5 of the answer from the link -
Django-Debug-Toolbar doesn't appear
I am trying a lot to appear Debug-tool but it doesn't appear. First I install it using pipenv: pipenv install django-debug-toolbar Here settings.py: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "BookListAPI", "debug_toolbar", # added debug-tool here ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", 'debug_toolbar.middleware.DebugToolbarMiddleware', # added debug_toolbar.middleware ] # added INTERNAL_IPS INTERNAL_IPS = [ '127.0.0.1', ] urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("api/", include('BookListAPI.urls')), path("__debug__/", include('debug_toolbar.urls')), ] I don't know why debug-tool doesn't appear. -
Can I get some assistance with a Django/SQLite3 schema?
I am trying to put together a Django app that will show the teams and games for my fantasy football league. I have taken a few cracks at the models, but I can't get my head wrapped around how they will relate. This is what I am trying to accomplish: Each year, there are six teams that make the "Toilet Bowl" tournament, which will crown the worst team in the league. There are three rounds. The worst two teams are not playing the first round. That leaves team 1 playing team 4 and team 2 playing team 3. In round 2, teams 1 and 2 play the losers from round 1. In round 3, the remaining two teams play for the title. These are the models that I have so far. I know that they're not optimal. class Owner(models.Model): name = models.CharField(max_length=200) email = models.EmailField(max_length=100) phone = models.CharField(max_length=12, null=True) def __str__(self): return "%s" % (self.name) class Team(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) name = models.CharField(max_length=200) def __str__(self): return self.name class Game(models.Model): year = models.SmallIntegerField( validators=[MinValueValidator(2010), MaxValueValidator(2999), RegexValidator("^(20)([1-5][0-9])$") ]) round = models.SmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(3)]) teams = models.ManyToManyField(Team) #teams = models.ForeignKey(Team, on_delete=models.CASCADE) #team1_score = models.IntegerField(default=0) #team2_id = models.ForeignKey(Team, on_delete=models.CASCADE) #team2_score = models.IntegerField(default=0) def … -
Django Rest Framework + SimpleJWT returns 401 on unprotected routes
I have configured DRF to use JWT as an authentication scheme and for the most part works correctly however when a user's token & refresh token are no longer valid rather than returning a 200 as an unauthorized user for unprotected routes and displaying the website as if they are no longer logged in the backend returns a 401. I am new to the Django auth scheme / middleware setup but my assumption would be that if the default is AllowAny then a bad token would be ignored. Is there a configuration that I am missing. From the DRF Docs If not specified, this setting defaults to allowing unrestricted access: 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] my settings.py REST_FRAMEWORK = { ... "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.BasicAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", ), } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": datetime.timedelta(minutes=15), "REFRESH_TOKEN_LIFETIME": datetime.timedelta(days=2), ... } Example ViewSet that returns 401 with bad access token class PromoApiSet(ViewSet): serializer_class = PromoSerializer def get_queryset(self, *args, **kwargs): time_now = timezone.now() return PromoNotification.objects.filter( end_date__gte=time_now, start_date__lte=time_now ) # @method_decorator(cache_page(120)) def list(self, request): promos = self.get_queryset() serializer = self.serializer_class(promos, many=True) promos_data = serializer.data response_data = {"promos": promos_data} return Response(response_data) -
Filtering broadcasts by date and category at the same time
I am developing a Django website and faced the following problem: I need to filter broadcasts by date (the date is specified by the user) and category. Screenshot: https://i.stack.imgur.com/5V1Or.png Could you tell me how to implement such a thing shown in the screenshot? Attempts to form a get request with parameters were unsuccessful -
change in fonts and spacing in a django app
I installed django bootstrap5 but it seems to have messed up the css and fonts and i can't seem to figure out what went wrong..I have a website am trying to clone, innitially things looked pretty the same until i tried installing django bootstrap and django tailwinds, well i later uninstalled tailwinds but the mess is still there. here is the pic of the changesThe current changes in the interface Here is what it looked like innitially and how the website itself looks like website fonts