Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
2 Django projects on one IIS server under the same domain name
My goal is to create a dev environment for a Django project that I inherited. It is hosted on an IIS server and there is currently only a production environment server-side, which is being used by the clients at my university. I want to have a copy of the entire site that I can use for testing purposes. This copy would also use a separate database, which is a copy of the current database with some added tables. My initial thought was to have another branch of the git repo in the wwwroot folder, something like this: wwwroot/prod/django_project_files_here wwwroot/dev/django_project_files_here Both of these would hopefully use the same domain name, but use different urls and views in their respective urls.py and views.py files. For example, app.uniname.edu/home would tap the production version, whereas app.uniname.edu/dev-home would tap the dev version. All of the urls in the prod version would have a similar dev version with "dev" added to the url. I thought I had this all set up, but all of the urls in the second/dev version were 404s. This leads me to believe that the server is not actually using the second copy of the Django application. Granted, I'm not sure that … -
how to run simultaneous docker commands using asynchronous Django RESTAPI call
I am building a B2C Django application where I need to build multiple docker containers for each customer. I can call a single "docker run -d" commands using os_command from my rest API in Django. I am hosting it in Ubuntu 18.04. I can make multiple API calls from Django but in my Ubuntu host, it will delay the Docker commands unless the previous command is executed fully. I want to run multiple "docker run -d" commands to build containers for my customers. Is it possible to do it using an Asynchronous API call or does the Ubuntu system have a limitation to execute multiple commands simultenously? -
emerg "http" directive is not allowed here & server_names_hash
I am currently setting up my nginx .conf file with the following code server { listen 80; server_name ec2-13-59-58-36.us-east-2.compute.amazonaws.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/Shiftly/app.sock; } } However when I run sudo nginx -t I get an error like so :Dec 16 11:38:08 netzmelone nginx[14242]: nginx: [emerg] could not build the server_names_hash, you should increase server_names_hash_bucket_size: 32 I then add this code at the bottom of my .conf file or in my server file http { server_names_hash_bucket_size 64; } However this returns an error of nginx: [emerg] "http" directive is not allowed here in /etc/nginx/sites-enabled/django.conf:11 -
django: How to display ForeignKey elements using ListView
How can I use ListView to display ForeignKey elements? I don't know how to write in a template, so please let me know. My code is below. exp/models.py from django.db import models from users.models import User import uuid class Experiment(models.Model): experiment_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) subject = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) start = models.DateTimeField(null=True) users/models.py class User(AbstractBaseUser, PermissionsMixin): uuid = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) exp/urls.py from django.conf.urls import url from django.urls import include, path from django.contrib.auth import views as auth_views from . import views app_name = 'exp' urlpatterns = [ path('exp_data/', views.ExpList.as_view(), name='exp1_data'), ] exp/views.py class ExpList(ListView): model = Experiment1 template_name = 'experiment1_list.html' experiment1_list.html <table border="1"> <tr> <th>Full name</th> <th>Email</th> </tr> {% for data in object_list %} <tr> <td> {{ data.subjec.first_name }} {{ data.subjec.last_name }}</p> </td> <td>{{ data.subject }}</td> </tr> {% endfor %} </table> Results ------------------- |Full name|Email | |---------|-------| | |a@a.com| |---------|-------| | |b@b.com| ------------------- Expected results -------------------- |Full name |Email | |----------|-------| |John Smith|a@a.com| |----------|-------| |Jane Smith|b@b.com| -------------------- -
How to add more fields to the return response in django rest framework
I am trying to add more fields to the Response in the django rest framework to send to react frontend. This works fine @api_view(('GET',)) def get_status(request, task_id): task = current_app.AsyncResult(task_id) response_data = ImageSerializer(Image.objects.get(pk=task.get())) return Response(response_data.data, status=status.HTTP_201_CREATED) How can I add the json context below to the Reponse also? #How can I add the following to my response too context = {'task_status': task.status, 'task_id': task.id} -
How to write an asynchronous task in react for celery and django rest framework?
Here is my frontend react which checks if the task is pending, if it is pending then call getStatus again, if it is not pending anymore then pass it on to showCalculation getStatus = (obj) => { axios.get(`api/task/${obj.data.task_id}/`, {headers: {'accept':'application/json', }}, ).then(resp => { (obj.data.task_status === 'PENDING') ? this.getStatus(obj) : this.showCalculation(obj) }) } Here is my Django rest framework task @api_view(('GET',)) def get_status(request, task_id): task = current_app.AsyncResult(task_id) if task.status == 'SUCCESS': response_data = ImageSerializer(Test.objects.get(pk=task.get())) return Response(response_data.data, status=status.HTTP_201_CREATED) # the else statement is returning an error else: response_data = {'task_status': task.status, 'task_id': task.id} time.sleep(5) return Response(response_data, status=status.HTTP_400_BAD_REQUEST) How can I fix my else statement to return a response to the frontend so it checks again? {data: {…}, status: 400, statusText: 'Bad Request', headers: {…}, config: {…}, …} config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …} data: {task_status: 'PENDING', task_id: '83938b81-4031-4522-ac56-23dd77b9ce6e'} headers: {content-length: '74', content-type: 'application/json'} request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status: 400 statusText: "Bad Request" [[Prototype]]: Object -
Mixed Content issue in Django
Getting the below error message while downloading the file from frontend , The front end url uses Https but the backend Django API url serving the file is http. New to django ,kindly help in sorting this out Mixed Content: The site at 'https://frontend.com/' was loaded over a secure connection, but the file at 'http://backend.com/user_summary/' was loaded over an insecure connection. This file should be served over HTTPS. -
What is the proper way of achieving a browsable API that expects data from 2 tables but writes to one and then another not in the first set of tables?
I have a Django project where I have 3 Models X: from django.contrib.postgres.functions import RandomUUID from django.db import models class X(models.Model): id = models.UUIDField(primary_key=True, default=RandomUUID) name = models.CharField(max_length=100) Y: from django.contrib.postgres.functions import RandomUUID from django.db import models class Y(models.Model): id = models.UUIDField(primary_key=True, default=RandomUUID) name = models.CharField(max_length=100) and XY: from django.contrib.postgres.functions import RandomUUID from django.db import models from my_app.models import X from my_app.models import Y class XY(models.Model): id = models.UUIDField(primary_key=True, default=RandomUUID) x_id = models.ForeignKey(X, on_delete=models.CASCADE, db_column='x_id') y_id = models.ForeignKey(Y, on_delete=models.CASCADE, db_column='y_id') and a default ModelSerializer for each of them: class XSerializer(serializers.ModelSerializer): class Meta: model = X fields = ['id', 'name'] class YSerializer(serializers.ModelSerializer): class Meta: model = Y fields = ['id', 'name'] class XYSerializer(serializers.ModelSerializer): class Meta: model = XY fields = ['id', 'x_id', 'y_id'] and I´d like to somehow, on get requests when retrieving X objects, to also show the XY objects related to it. On POST requests though, I'd like to be able to send the data for the X object with a nested field of many id's from the Y table and create an X object, retrieve the newly generated primary key of that X object and create as many XY objects as Y primary keys were sent with that … -
React to "click event" in Python (Django)
everyone, beforehand - I'm a bloody but motivated developer beginner. I am currently trying to react to simple events (click on a button) in the HTML code in my Django project. Unfortunately without success ... HTML: <form> {% csrf_token %} <button id="CSVDownload" type="button">CSV Download!</button> </form> JavaScript: <script> document.addEventListener("DOMContentLoaded", () => { const CSVDownload = document.querySelector("#CSVDownload") CSVDownload.addEventListener("click", () => { console.dir("Test") }) }) </script> Do I need JavaScript for this? Or is there a way to react directly to such events in python (Django)? I am really grateful for all the support. Since I'm not really "good" yet - a simple solution would be great :) Python (Django) if request.method == "POST": projectName = request.POST["projectName"] rootDomain = request.POST["rootDomain"] startURL = request.POST["startURL"] .... With this, for example, I managed to react to a kind of event, i.e. when the user sends the form. The problem here, however, is - if I have several forms on one page, then I cannot distinguish which function should be carried out: / I am at a loss -
Django Database issues after deploying to Heroku
I am having this issue below since deploying to Heroku. Depending on the page, the model causing the error changes, but the issue is still the same across. The example I will provide, gets triggered from the trailer-locations/ page. Environment: Request Method: GET Request URL: https://nameless-ravine-45956.herokuapp.com/trailer-locations/ Django Version: 3.2.6 Python Version: 3.10.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.home', 'apps.config'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (column home_trailerlocation.statusCode does not exist LINE 1: ...State", "home_trailerlocation"."locationCountry", "home_trai... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/app/apps/home/views.py", line 103, in trailerLocations timestamp = trailers[0]['trailerlocation__updated_at'] File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 317, in __getitem__ qs._fetch_all() File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 109, in __iter__ for row in compiler.results_iter(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1130, in results_iter results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 98, in … -
Django - Annotating an aggregation of annotations on related objects
I have three models: class Document(BaseModel): def total_price() return DocumentLine.objects.filter( section__in=self.sections.all() ).total_price() class Section(BaseModel): document = ForeignKey(Document, on_delete=CASCADE, related_name='sections') class LineQuerySet(QuerySet): def with_total_price(self): total_price = F('quantity') * F('price') return self.annotate( total_price=ExpressionWrapper(total_price, output_field=DecimalField()) ) def total_price(self): return self.with_total_prices().aggregate( Sum('total_price', output_field=DecimalField()) )['total_price__sum'] or Decimal(0.0) class Line(BaseModel): objects = LineQuerySet.as_manager() section = ForeignKey(Section, on=delete=CASCADE, related_name='lines') price = DecimalField() quantity = DecimalField() As you can see on the LineQuerySet, there is a method that will annotate the queryset with the total price of each line, based on the price and quantity. Now I can easily get the total price of an entire document doing something like this: document = Document.objects.get(pk=1) total_price = document.total_price() However, now I would like to generate a queryset of multiple documents, and annotate that with each document's total price. I've tried a combination of annotates, aggregates, making use of prefetch_related (using Prefetch), and OuterRef, but I can't quite seem to be able to get the result I want without it throwing an error. Is there some way to perform this operation in a queryset, making it then possible to filter or order by this total_price field? -
Django views page not found
I am trying to get the task_id of celery but the URLs is returning error not found Here is my URLs router = routers.DefaultRouter() router.register(r'analyze_im', ImageViewSet) urlpatterns = [ path('', include(router.urls)), path('task/<str:task_id>', TaskView.as_view()), ] Here is my serializer class TaskView(View): def get(self,request, task_id): task = current_app.AsyncResult(task_id) response_data = {'task_status': task.status, 'task_id': task.id} if task.status == 'SUCCESS': --some logic-- return JsonResponse(response_data) When I navigate to /api/analyze_im/task/e11c2a1d-91b6-44c7-befd-663884753d52it show Page not found (404) The current path, didn’t match any of these. , why is that? When I do the following http://localhost:8000/api/analyze_im/task/ Django shows me the API view -
In Django, how can I have a function where I can only update the value instead of creating a new instance of it?
For example, I have a function in my views.py to post availability of food. However, I do not want the user to keep creating new instances of available food. I only want the user to be able to update that value. Right now, I have restricted the user to just create a food availability instance and then am not allowing the user to create another one. However, I do not want it as such; I want the user to be able to just update that number. This is what I have now: def check_existing_post(request): data = request.POST.copy() data["author"] = request.user if len(Food_Avail.objects.filter(author=request.user)) > 0: return False else: return True def post_available_food(request): instance = Food_Avail() data = request.POST.copy() data["author"] = request.user form = FoodAvailForm(data or None, instance=instance) if request.POST and form.is_valid() and check_existing_post(request): form.save() return HttpResponseRedirect(reverse("accounts:home")) else: messages.info( request, "food availability by restaurant has already been posted!" ) return render(request, "food_avail/post_food_avail.html", {"food": form}) -
Django looking for static files in contrib/admin and ckeditor
My app doesn't serve the embedded static files in my HTML my project structure is: main/ mediafiles/ resume/ settings.py ... static/ css/ images/ js/ settings.py: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "main", "ckeditor", ] STARICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'media'), ] STATIC_URL = "/static/" STATIC_ROOT = BASE_DIR / "staticfiles" MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "mediafiles" However, when I try python manage.py findstatic --verbosity 2 static/js/style.js I get the following: No matching file found for 'js/script.js'. Looking in the following locations: C:\Users\Bilal\Envs\django-env\lib\site-packages\django\contrib\admin\static C:\Users\Bilal\Envs\django-env\lib\site-packages\ckeditor\static Any idea where I might be going wrong? All the static file settings appear to be correct. Any help will be appreciated as I've been stuck on this one for a while -
Reduce db queries
my models class AssessmentTest(BasicModel): title = models.CharField(max_length=120, unique=True) class UserTestResult(BasicModel): assessment_test = models.ForeignKey(AssessmentTest, on_delete=models.CASCADE, related_name='users_passed') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='test_results') points = models.PositiveIntegerField(default=0) my views class AssessmentTestView(ReadOnlyModelViewSet): serializer_class = AssessmentTestSerializer queryset = AssessmentTest.objects.all() my serializers class AssessmentTestListSerializer(serializers.ModelSerializer): class Meta: model = AssessmentTest fields = [ 'id', 'title', 'user_results', ] user_results = serializers.SerializerMethodField() def get_user_results(self, obj: AssessmentTest): user = self.context['request'].user if not user.is_anonymous: test_result = UserTestResult.objects.filter(assessment_test=obj, user=user) if test_result: return UserTestResultSerializer(instance=test_result.last()).data return None When I try to get all tests, in get_user_results I face n+1 problem (for every test there is extra query to UserTestResult) Can I somehow avoid this? Maybe it's possible to use prefetch_related on reverse foreign_key in queryset? Or not? Can someone help? -
Check for a specific url and render jinja2 / html
How can check for a specific URL in jinja2 within html files and then render different html files based on what URL I am currently at? For eg. # if {{ request.path == /siteID/ }} {% include "file1.html" %} # if {{ request.path == /siteID/abcde/ }} {% include "file2.html" %} Current logic I have which I feel is not very good: <!-- ..... bunch of html lines .... --> {% if request.path|length > 8 and request.path.startswith('/siteID/') and request.path[8:].strip('/').split('/')|length == 1 %} {% include "file2.html" %} {% else %} {% include "file1.html" %} {% endif %} <!-- ..... bunch of html lines .... --> Also how do I scale this if I want to do something in the future like: # if {{ request.path == /siteID/abcde/uvwxyz }} {% include "file3.html" %} -
Advice on adding an ancestors ArrayField to a self-referential model in Django
I'm developing a Django app (Django 3.2.8, Python 3.9, PostgreSQL 13.4) that functions very much like an FTP service. For the folder/file structure I've created a self-referential model called "Instance", which also uses generic relations so that I can reuse/structure various content types under one another: class Instance(models.Model): parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') subscribers = models.ManyToManyField('users.Organization', blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') However, I'm finding that development is being limited/slowed by the need for raw CTE queries. And I'm thinking that the most elegant way (based on the views I require) to make this model fully ORM-accessible is to add an "ancestors" ArrayField. class Instance(models.Model): parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') ancestors = ArrayField(models.PositiveIntegerField(), null=True, blank=True, default=list) .... I was easily able to construct & add an array value to this field through my views/scripts with a function like: def get_ancestors(context_instance, ancestors_array): ancestors_array.append(context_instance.id) if context_instance.parent: return get_ancestors(context_instance.parent, ancestors_array) else: return list(reversed(ancestors_array)) However, I thought it would be far better to have the ancestors array value calculated and added whenever an instance of the "Instance" model was saved. I couldn't figure how it would be possible to query instances of a model … -
Django ValueError: too many values to unpack (expected 2)
I am a beginner on Django and I need help on my django 2.2 application. I have virtual machines and schedules with a manytomany relationship. I am trying to create a new schedule but I have an error. Basically in my schedule creation form in a column I display the list of VMs. So we can select which machine to assign a schedule. But what I would like is to display in another column the existing schedules, like this(Picture) :https://ibb.co/2dvTzXc I tried with a raw query, It's display well, but When I tried to send my form an error occured:My traceback = https://dpaste.org/p9SQ My models = https://dpaste.org/FwFe My code = https://dpaste.org/ZsNZ # MY TEMPLATE {% for i in form.vms.field.choices %} <tr class="clickable_vm"> <td> <label for="{{ i.0 }}"> <input type="checkbox" name="vms" value="{{ i.0 }}" class="displaynone" id="{{ i.0 }}">{{ i.1 }} </label> </td> <td class="schedule-name">{% for j in i.2 %}{{ j }}<br/>{% endfor %}</td> </tr> {% endfor %} # MY RAW QUERY cursor = connection.cursor() cursor.execute( ' SELECT vmware_virtualmachine.id,' ' vmware_virtualmachine.name,' ' group_concat( appli_vmschedule.schedule) as "schedule"' ' FROM vmware_virtualmachine' ' LEFT OUTER JOIN appli_vmschedule_vms' ' ON (vmware_virtualmachine.id = appli_vmschedule_vms.virtualmachine_id)' ' LEFT OUTER JOIN appli_vmschedule' ' ON (appli_vmschedule_vms.vmschedule_id = appli_vmschedule.id)' ' group by … -
Upgrading to django 3.2 breaks API tests (response.data['detail'])
I'm upgrading our django app from 3.0.5 to 3.2.9, and I'm having some issues with API tests. The response returned has apparently changed, and I would like to know why. self.user.is_superuser = False self.user.save() self.assertEqual(self.user.get_all_permissions(), set()) put_url = reverse(..., kwargs={"pk": 1}) put_data = { ... } response = self.client.put(put_url, json.dumps(put_data), content_type="application/json") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual(response.data, {"detail": "You do not have permission to perform this action."}) This used to pass, but now response.data contains {'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')} and of course the tests fail. The odd thing is that the error code remains 403, not 401. Is there a way to just have the string returned in detail? -
I would like to display only one post at fronted (dajngo framework)
I have posted several posts but am unable to display only one post at the front end from several posts. instead, it displays all the post which is not correct. help appreciated, thank you views.py def ann(request): ann = Announcement.objects.all() context = { 'ann': ann } return render(request, 'Announcement.html', context) index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Community</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <!-- Font Awesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css" /> <link rel="stylesheet" href="{% static 'css/bootstrap@5.1.3.css' %}"> <!-- Style.css --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> {% block content %} {% include 'navbar.html' %} {% for ann in ann %} {% if forloop.first %} <div class="col-12 col-lg-10 col-xl-10 col-sm-10" style="margin: auto;"> <div class="row"> <div class="card-body"> <h4 class="card-title" style="text-align: right; border-bottom: 2px solid; color: #46a271; padding: 17px; overflow: hidden; top: 0; z-index: -1000; "> <p style="color: #0e3d42;">Category: {{ann.name}}</p> </h4> <br> <p class="card-text" style="text-align: center;">{{ann.body|safe}}</p> <p> Post created on {{ann.created_date}}</p> </div> </div> </div> {% endif %} {% endfor %} <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> {% include 'footer.html' %} {% endblock %} <!-- Scripts --> <script src="{% static 'jquery/jquery-3.5.1.slim.min.js' %}"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script> <!-- Custom Script --> <!-- <script> function truncateText(selector, maxLength) … -
Django/Python requirements.txt issue with DigitalOcean
I have set up an Ubuntu 18 droplet. When I got to install my django project requirements I hit issues with some of the packages - for example: ERROR: Could not find a version that satisfies the requirement anyjson==0.3.3 (from versions: 0.1, 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.2.5, 0.3, 0.3.1, 0.3.2, 0.3.3) ERROR: No matching distribution found for anyjson==0.3.3 Which is confusing because the version is listed is the "from versions" list. Anyone come across this before? -
Query accessing custom model method - Django ORM
I have 2 models that are relevant to this question: class ParkingOrder(models.Model): # main order that could pay for multiple parkers id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False, primary_key=True) timestamp = models.DateTimeField(null=True, blank=True) status = models.CharField(max_length=15) stripe_charge_id = models.CharField(max_length=150) wallet = models.CharField(max_length=100, null=True, blank=True) # if mobile wallet was used for order (Apple Pay, Google Pay, etc.) def __str__(self): return str(self.id) def walletdisplay(self): return self.wallet.replace('_', ' ').title() class ParkingSession(models.Model): # attributes of a single parker parking_duration = models.ForeignKey(ParkingOption, on_delete=models.PROTECT) parking_order = models.ForeignKey(ParkingOrder, on_delete=models.PROTECT) #refernce which order it belongs to price = models.IntegerField(null=False, blank=False) # store price in pennies license_num = models.CharField(max_length=20, blank=False, null=False) def __str__(self): return str(self.parking_duration) + " - " + str(self.parking_order) + " - " + str(self.license_num) I am trying to query a dictionary of all the wallet types. ParkingSession.objects.filter(parking_order__status='Paid').exclude(parking_order__wallet='No wallet').values('parking_order__wallet').order_by('-parking_order__wallet').annotate(count=Count('parking_order__wallet')) The above query works great but I want the walletdisplay method instead of the wallet attribute. This is because Stripe returns 'apple_pay', 'google_pay' instead of 'Apple Pay', 'Google Pay'. I have tried this, but it throws an error saying that 'walletdisplay' is not an option: ParkingSession.objects.filter(parking_order__status='Paid').exclude(parking_order__wallet='No wallet').values('parking_order__walletdisplay').order_by('-parking_order__walletdisplay').annotate(count=Count('parking_order__walletdisplay')) How can I access the foreign key custom method in the query? -
Get data from specific account_id from Django Manager
I want to have a global manager who return only data from specific account_id This is my globalManager : class GlobalManager(models.Manager): def get_queryset(self): model_name = self.model.__name__ queryset = GlobalQuerySet( model=self.model, using=self._db, hints=self._hints ).filter(is_deleted=False, account_id=account_id) And I call my manager from my model like this : class myClass(models.Model): id = models.AutoField(primary_key=True, editable=False, unique=True) name = models.CharField(max_length=100) objects = GlobalManager() The value of the account_id is available in the header of the request My problem is to provide this account_id to my manager or to my model ! Tech stuff: django==2.2.8 graphene==2.1.8 Thanks -
Time and date stopped updating "python django gunicorn nginx"
Time and date stopped updating after gunicorn restart in a few minutes To not update the time and date again, I also need to restart gunicorn Use nginx on digitalocean for info too for example Now I updated my code and uploaded it to the server I will run the command "sudo systemctl reset gunicorn" To see my update Now you have requested the time and date | looks like this 10:30 at 10:30 that's right But after a few minutes I'm dialing the time and date again It shows 10:31 but it's 10:50 It stops updating completely until I restart "sudo systemctl restart gunicorn" At this time, the time update comes and also some minutes and stops for a while!! -
How to output multiple days as one event using HTMLcalendar
I am using the calendar function using HTMLcalendar module in django. I want to output only one event in a straight line on the calendar when more than 2 days are specified using the 'leave_date' and 'leave_end_date' datefields. Currently, in the code below, an event is added to each of the days corresponding to the period. ex) leave_date: '2021-11-03', leave_end_date: '2021-11-07' #filter events by day I think this part should be corrected, please help! [urls.py] from django.urls import path from . import views app_name = 'leave' urlpatterns = [ path('calendar/', views.CalendarView.as_view(), name='calendar'), # /leave/calendar path('calendar/new/', views.leave, name='leave_new'), # /leave/calendar/new path('calendar/edit/<int:leave_id>/', views.leave, name='leave_edit'), # /leave/calendar/edit/{} path('calendar/delete/<int:leave_id>/', views.leave_delete, name='leave_delete'), # /leave/calendar/delete/{} ] [models.py] from django.db import models from django.urls import reverse class Leave(models.Model): name = models.CharField(max_length=50, blank=True, null=True) leave_date = models.DateField(blank=True, null=True) leave_end_date = models.DateField(blank=True, null=True) take_over = models.TextField(blank=True, null=True) memo = models.TextField(blank=True, null=True) is_deleted = models.BooleanField(default=False) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) @property def get_html_url(self): url = reverse('leave:leave_edit', args=(self.id,)) return f'<a href="{url}"> {self.name} </a> <a data-toggle="modal" data-target="#detail_leave_{self.id}">Detail</a>' [forms.py] from django.forms import ModelForm, DateInput from .models import Leave class LeaveForm(ModelForm): class Meta: model = Leave # datetime-local is a HTML5 input type, format to make date time show on fields widgets = …