Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I make a Django query that spans two tables?
class Listing(models.Model): title = models.CharField(max_length=64) description = models.TextField() starting_bid = models.DecimalField(max_digits=10, decimal_places=2) image = models.URLField() category = models.CharField(max_length=64) user = models.ForeignKey(User, on_delete=models.CASCADE, default=0) is_active = models.BooleanField(default=True) class Bids(models.Model): bid = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listing_bids") value = models.DecimalField(max_digits=10, decimal_places=2, default=0) user = models.ForeignKey(User, on_delete=models.CASCADE, default=0) I'm trying to write a query who's result would be an QueryList that has all the "title"'s from from the Listing table associated with the max "value"'s for each of the "bid"'s in the Bids table. Right now I can create a list of dictionaries that is basically functional, but it involves multiple queries and a bunch of hacking up of those queries with loops and zips. I have a hunch this can be done in a single query, because I'm pretty sure I could write the raw SQL query with JOIN, WHERE and MAX. My ideal result would be something like <QuerySet: ['('Cat': '3')......]> I know I need to use some combination of filter, aggregate(Max) and annotate(?), but i'm just not sure where to go with it. Any pointers or input would be greatly appreciated, let me know if you need to see anything else in my code. I have a Django query that will return … -
Visual Studio not reading from Environmental Variables
When I call the os.environ.get('SECRET_KEY_1') in Visual Studio it returns None. I am trying to hide my Django SECRET_KEY by storing it as an Environmental variable. I also noticed if I run the exact command to test in pycharm, it returns the exact key but doing the same under visual studio code which I'm using returns None. -
How to set a timeout to interrupt the calling method in python?
I want to set a timeout in the view, if the code execution in the view exceeds the timeout # urls.py url(r'^test-api/$', test_api_view) # views.py from rest_framework import status from rest_framework.response import Response def test_api_view(request): timeout=10 data = someMethod() if xxx: # Call some_method() for more than 10 seconds, and the method call may not end return Response({"error": "Timeout"}) else: return Response(data) -
Beginner - Python apps
I am working on a project of my own and since I am a beginner I was trying to understand how to create apps in the project for example I have an app for login/logout/signup which is called 'User'. Now, for the next part of the project, I want to have a page that will have all the items listed from the database on the webpage but should I create that in a separate app or can it be done in the user app? Or what is a better practice? -
Formset Rendering on a Many To Many Through Model
I'm trying to properly render a formset for a many to many through model. I have "Tickets" model that contains many "Products". I have a custom model for "TicketProducts" since I have a count field on each "TicketProduct" (the number of the specific product that is on the ticket). I would like to create a single page with both a save for a ticket as well as a save for each potential ticket product. I run into issues when I am trying to render every single product as a formset, where somebody can go in and list how many products that they would like for their ticket. I have tried splitting apart the logic into a "Ticket" page and a "TicketProduct" page, where ticketProducts are listed using a simple for loop through all products. However, this creates additional issues trying to add forms in my template through a loop. Is there a way to render all of the products, as well as a field to input a count, and still allow it to be saved? Is the solution something beyond forms, or is a formset the best option? models.py class Product(models.Model): product_id = models.AutoField(primary_key=True) upc_code = models.CharField(max_length=200) product_name = models.CharField(max_length=200) … -
How can I fix this error? Field 'id' expected a number but got 'aapl'
I'm trying to create a stock blog page and right now in this project, I'm having problems with the url thing, because what I want to do is that for each post created in each stock name, I want to show the post in that page, my explanation may be a little confusing, but here's the code and the error so you can see. Error Traceback (most recent call last): File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\snin2\Desktop\basura\lapagina\app1\views.py", line 59, in StockView stock_posts = Post.objects.filter(stock=sym.lower()) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1311, in build_filter condition = self.build_lookup(lookups, col, value) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup lookup = lookup_class(lhs, rhs) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\lookups.py", line 22, in __init__ self.rhs = self.get_prep_lookup() File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\related_lookups.py", line 115, in get_prep_lookup self.rhs = target_field.get_prep_value(self.rhs) File "C:\Users\snin2\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\__init__.py", line … -
How to write a unit test a custom Filter in Django rest framework?
I am new to Django, so maybe this is very simple, but I have been trying to make sense of the documentation all day and I need some help, some way to going in the right direction. Basically, I have a Custom Filter class, like this class CustomFilter(django_filters.rest_framework.FilterSet): username = BooleanFilter(method='filter_current_user') ... And inside, several methods, being the following the simpler of them def filter_current_user(self, queryset, name, value): if value is True: return queryset.filter(user=self.request.user) return queryset How can I write a test that validates the differences of the queryset returned when value is True and when value is False? My biggest problem is how make that the self value contains the request.user. -
Django admin page layout changed with new version
I am working on an existing django project where admin console is extensively used. With my latest run of package upgrade for my application admin page layout has changed. Models have started appearing on all the pages, leaving a small space to display form fields. For example this is how form page look like now: Original Form view was occupying the whole page like this: Any clue on what has been changed and which setting to change to get back the original view? -
Consult JSONField with Django filter backends in ListModelMixin
I would like to consult a JSONField field from the URL of an endpoint in django rest framework and for it to return the match that exists within a JSONField field of the model. The following is the model: class TestJsonGuard(models.Model): idtest = models.AutoField(primary_key=True) product = models.CharField(max_length=100) json_leader = JSONField() The following is the view from where I want to make the query: class TestGuardJson(mixins.ListModelMixin,generics.GenericAPIView): permission_classes = (permissions.AllowAny,) queryset = TestJsonGuard.objects.all() serializer_class = TestJsonGuardSerializer parser_classes = (MultiPartParser,) filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ["product", "json_leader"] search_fields = ["product", "json_leader"] pagination_class = Pagination def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) I am trying to send something like this from url: /api/v1/test?json_leader__active_substance__contains=VITAMINA C But this does not work for me to find the matches in the JSONField stored in the database, whose structure is: [{"active_substance": "VITAMINA D"}, {"active_substance": "VITAMINA A"}, {"active_substance": "VITAMINA B"}] The error that throws me when trying to consult it that way is: AutoFilterSet resolved field 'json_leader' with 'exact' lookup to an unrecognized field type JSONField. Try adding an override to 'Meta.filter_overrides'. How could I configure the view properly without affecting the other fields that the model owns and that can be queried in them? -
Django doesnt generate migration file for newly created model
I am new to Django. I created a new model file called abc.py in my project. In this there are 3 Models A , B, C. Now when I run ./manage.py makemigrations it doesnt generate migration file. To over come this i added an import statement in __init__.py in the containing folder of this abc.py stating from models.abc import * now if I run ./manage.py makemigrations it creates a new migration file. Is this expected? Another question once the migration file got generated i removed contents of init.py taught django always looks for migration file. Now in my continuous integration system. we run python python manage.py makemigrations --dry-run --no-input --verbosity 3 --check as a precheck. This command is giving error status 1 and tries to remove the newly created tables. How can. i overcome this -
django exception handling causes standard output to hang/site to stop updating?
In development mode, if I handle an exception in a view like this except Exception as e: print("An unexpected error occured") messages.error( request, f'Failed completely. Please try again or contact a developer.' ) logger.error(traceback.format_exc()) return redirect('failure') When the console catches this message, I cannot see any more http requests logged to the console and automatic updates to the site no longer register. The redirect is happening and the server still functions and routes everything correctly after, but I no longer see GET requests logged. I am afraid this will affect the production server as well (once the error is popped, all logging may stop?) Is this normal for development in Django? I feel that exception handling should not hang stdout. -
Cron Job with Django and Elastic Beanstalk
I want to create a Cron Job to run every day at 6:00 am PST. I am using Django and hosting on Elastic Beanstalk AWS. How do I get started? I have tried django-cron but can't find a good example. Thanks! -
Django: chart.js, how to use time as x-axis?
I have successfully implemented chart.js to take my data from the database and add them to the chart! but now, I'm trying to make some changes to my x-axis. Here, From the table on the left, I put my mark in, and the table on the right should visualize my data. However, as you might have noticed, I wanted to fix the x-axis label from January to December, but the date for the marks should remain @ Aug. 12th. (but on the graph, the points are plotted once every month, which is obviously not what I want). my code for the graph is, <canvas id="chart" width="800" height="500"></canvas> <script> var ctx = document.getElementById('chart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: ['jan','feb','mar','apr','may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'], datasets: [{ label: 'Total Year Academic Performance', data: {{ data|safe }}, fill: false, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 … -
Force Entry of Password When Deleting On Admin
I am new to Django and I'm wondering if there is any way to force the entry of a superuser's password before deleting stuff on admin. Thanks! -
Django WSGI Error Saving Model Choice Field in Admin
This doesn't break the application or throw up any errors in the Django admin, but I get the following line in my apache error log and am not sure why or if it even matters: [Wed Aug 12 20:49:29.414991 2020] [wsgi:error] [pid XXXXX:tid XXXXXXXXXXXXXXX] [remote XX.XX.XX.XX:XXXXX] OPTION1 [Wed Aug 12 20:49:51.635383 2020] [wsgi:error] [pid XXXXX:tid XXXXXXXXXXXXXXX] [remote XX.XX.XX.XX:XXXXX] OPTION2 [Wed Aug 12 20:50:11.403505 2020] [wsgi:error] [pid XXXXX:tid XXXXXXXXXXXXXXX] [remote XX.XX.XX.XX:XXXXX] OPTION1 OPTION1 and OPTION2 are entries in a Django model CharField populated from a choices tuple set in the model. It doesn't appear to be affecting the application, but it is filling up my error logs. It only seems to happen on hard-coded choice fields, not when the choice is a foreign relation. -
How to make django Web App (local) turn in to desktop app
I see a lot of software that can make your web app turn to desktop app but only works on web app that is running online. but is there a way or software that can make my web app to desktop app in local (offline)? I'm using Django for my development. -
Why does a function in views.py require a request parameter in this case in Django?
In url.py I have set up a new path within the main urlpatterns list: path('ko/', views.ko), I learned that I need to write this function in views.py to get the webpage going: def ko(request): return HttpResponse("It's a page") My question is why doesn't the function work when I leave the parameter blank instead of request?: def ko(): return HttpResponse("It's a page") Running the page when I delete the request parameter outputs a TypeError:ko() takes 0 positional arguments but 1 was given. If I don't have a request input on the function call of views.ko then why is the request parameter necessary when writing the initial function, what is the request parameter doing, and where is this request parameter going into? What are its attributes? I would really appreciate a thorough response on its qualities. -
Pycharm - no django tests found but run in console
I followed this tutorial https://docs.djangoproject.com/en/3.0/intro/tutorial05/ The tests can be run by the command (polls is the application name) python manage.py test polls However under PyCharm IDEA, when I click on the green arrow (line 21-22). The message is "No tests were found" The stack trace is gibberish to me Traceback (most recent call last): File "/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pycharm/_jb_unittest_runner.py", line 35, in sys.exit(main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py", line 100, in init self.parseArgs(argv) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py", line 147, in parseArgs self.createTests() File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/main.py", line 159, in createTests self.module) File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 220, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 220, in suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/loader.py", line 154, in loadTestsFromName module = import(module_name) File "/Users/raychenon/Projects/python/django/mysite/polls/test_views.py", line 8, in from .models import Question File "/Users/raychenon/Projects/python/django/mysite/polls/models.py", line 8, in class Question(models.Model): File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 107, in new app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/usr/local/lib/python3.7/site-packages/django/conf/init.py", line 76, in getattr self._setup(name) File "/usr/local/lib/python3.7/site-packages/django/conf/init.py", line 61, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. … -
How to include OneToOne children in nested ModelForm
I am trying to create a ModelForm with conditional OneToOne children models included. For context, I've summarized the relevant parts of my models as follows: models.py class Quote(models.Model): ... class ScreenOperationType(models.Model): ... class Screen(models.Model): quote = models.ForeignKey(Quote, on_delete=models.PROTECT) operation_type = models.ForeignKey(ScreenOperationType, on_delete=models.PROTECT) ... class ScreenMotor(models.Model): screen = models.OneToOneField(Screen, on_delete=models.PROTECT) ... class ScreenCrank(models.Model): screen = models.OneToOneField(Screen, on_delete=models.PROTECT) ... A Quote can have any number of Screens. A Screen has one of four operation types: motor, crank, fixed, or none. A ScreenMotor child record only exists if the operation_type is 'motor', a ScreenCrank child record only exists if the screen operation_type is 'crank.' If the operation is fixed or none, no child records exist. I want to create all the nested records with the same form. I have built a form for the Quote with child Screen inline formset, but how do I include fields for ScreenMotor and ScreenCrank in the Screen ModelForm? I've tried writing a ModelForm for ScreenCrank and ScreenMotor, but nesting them as another formset doesn't seem to produce the desired results, assumedly because they are OneToOne. I know I will have to write javascript to show/hide inputs for the children, but for now I'd be thrilled to just … -
Ajax Get request not working when fetching HttpResponse from Django views
I'm experimenting a little bit with Django and Ajax. I want to make a simple view with a button that when someone clicks on it, the website alerts the data taken from another view in my views.py, which is an HttpResponse that says "foo". Currently, when I click on the button, nothing appears. I was wondering what has gone wrong here. My code is as follows: In my views.py: from django.shortcuts import render from django.http import JsonResponse from django.http import HttpResponse # Create your views here. def index(request): return render(request,"ajax/index.html") def test(request): return HttpResponse("foo") In my index.html: <body> <div> hello world </div> <button class="btn"> click this </button> </body> <script> $(".btn").click(function(){ $.ajax({ url: '//http://127.0.0.1:8000/test/', type: 'GET', success: function(data) { alert(data); }, error: function(jqXHR, textStatus, errorThrown) { alert("something went wrong") } }); }); </script> In my urls.py: from django.contrib import admin from django.urls import path from ajax import views as ajax_views urlpatterns = [ path('admin/', admin.site.urls), path('index/',ajax_views.index,name="index), path('test/',ajax_views.test,name="test") ] Thank you for your time! -
How to modify Djano' settings.py file to point to database file in AWS S3, the app being hosted at Heroku?
My Django web app is hosted at Heroku; the Postgresql database, that my app is dependent on, is hosted at an S3 bucket. I understand I have to use boto3 library to make my app access the S3 storage. I already have configured AWS_KEY and AWS_SECRET_KEY in heroku's CONFIG_VARS; I just need to know the proper way to tell the app (in Django's settings.py file) to access S3. -
ValueError: attempted relative import beyond top-level package - when import file
python 3.7.7 and also tried on python 3.6.0 I am using Django server, and in my views.py I am trying to get my function that in the detector. By file when I try to import my detector file: from ..DataFromSkyDetector import Detector ValueError: attempted relative import beyond top-level package it's raised this error: ValueError: attempted relative import beyond top-level package I am adding a picture of the hierarchy, I already added all the routes init.py. i, I made my detector file as a package and return it to a file, I read every stackoverflow question that regarded to this problem. [photo : 1 -
compose file is incompatible with Amazon ECS
I am trying to deploy my docker image in AWS ECS. I have created the ecs repo and done all required steps till pushing the image to ecs. My docker-compose.yaml looks like this version: '3' services: djangoapp: image: xxxxx.dkr.ecr.ca-central-1.amazonaws.com/abc:latest #uri after pushing the image build: . volumes: - .:/opt/services/djangoapp/src - static_volume:/opt/services/djangoapp/static # <-- bind the static volume - media_volume:/opt/services/djangoapp/media # <-- bind the media volume networks: - nginx_network - database1_network depends_on: - database1 nginx: image: nginx:1.13 ports: - 80:5000 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/opt/services/djangoapp/static # <-- bind the static volume - media_volume:/opt/services/djangoapp/media # <-- bind the media volume depends_on: - djangoapp networks: - nginx_network database1: image: postgres:10 env_file: - config/db/database1_env networks: - database1_network volumes: - database1_volume:/var/lib/postgresql/data networks: nginx_network: driver: bridge database1_network: driver: bridge volumes: database1_volume: static_volume: # <-- declare the static volume media_volume: # <-- declare the media volume I am trying to run the command: docker ecs compose -n abc up And i get the following error: WARN[0000] services.build: unsupported attribute WARN[0000] services.volumes: unsupported attribute ERRO[0000] published port can't be set to a distinct value than container port: incompatible attribute WARN[0000] services.volumes: unsupported attribute WARN[0000] services.env_file: unsupported attribute WARN[0000] services.volumes: unsupported attribute WARN[0000] networks.driver: unsupported attribute WARN[0000] networks.driver: unsupported … -
Django: Where to store own written scripts
I have recently started with the Django framework. I have some custom python scripts (could also later be custom packages) that I want to use. Where to I store them? (I want to import them in certain django .py files) I know in the framework you can have templates, static and media folders to keep various files. Would your own custom scripts sit in here or do you keep them somewhere else? (like in static where your css and js files sit) Can I just create a folder in the project called modules/py_scripts or is there a specific standard? Thanks in advance! -
Error in creating issue via jira rest api
I am trying to use create_issue to create a jira ticket via code from my python console but I am getting the error as "No project could be found with id" jira pip version -> 2.0.0 from jira import JIRA jac = JIRA('https://company_name.atlassian.net') jac.create_issue(project='39684', summary='New issue from jira-python',description='Look into this one', issuetype={'name': 'Bug'}) I got the project id 39684 using the following GET API https://company_name.atlassian.net/rest/api/3/project/project_key Please suggest where I am doing wrong.