Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django API that receives informaion [closed]
I have a problem at work, can anyone suggest training in this regard? Implement an django API that receives a person's general LinkedIn information (in linkedin) as GET and stores it in a sqlite database. -
python 3.7-compatible versions of azure-storage-blob
I'm running very simple django test server that just uploads and downloads files from and to azure-storage-blob. It works with one very old python virtual environment, that cannot be created any more due to some "deprecated errors". When letting pip choose the version of azure-storage-blob I get the following error when uploading with my simple django server: Environment: Request Method: POST Request URL: http://ramen.stat.fi:8037/uploads/form/ Django Version: 2.2 Python Version: 3.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'uploads.core'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/requests/packages/urllib3/util.py" in _validate_timeout 148. float(value) During handling of the above exception (float() argument must be a string or a number, not 'tuple'), another exception occurred: File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/azure/storage/common/storageclient.py" in _perform_request 333. response = self._httpclient.perform_request(request) File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/azure/storage/common/_http/httpclient.py" in perform_request 92. proxies=self.proxies) File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/requests/sessions.py" in request 361. resp = self.send(prep, **send_kwargs) File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/requests/sessions.py" in send 464. r = adapter.send(request, **kwargs) File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/requests/adapters.py" in send 307. timeout = TimeoutSauce(connect=timeout, read=timeout) File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/requests/packages/urllib3/util.py" in __init__ 120. self._connect = self._validate_timeout(connect, 'connect') File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/requests/packages/urllib3/util.py" in _validate_timeout 151. "int or float." % (name, value)) During handling of the above exception (Timeout value connect was (20, 2000), but it must be an int or float.), another exception occurred: File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/django/core/handlers/exception.py" in … -
chat application is working on simple consumers.py and room.html but not working in customized consumers.py and room.html
I am developing a chat app using vscode. The problem is, when i am running the application it is opening in browser but not sending or receiving messages and also it doesn't show any error message. I am new here and so not understanding what I will do now? The fact is, when I am using simple chat template and simple consumers.py, it is working fine but not working when I am using a customized chat template and customized consumers.py. Yet click is not taking any effect on send message but is is sending and receiving messages on shel(i.e; channel is working fine). I think the problem is in customized consumers.py and romm.html. Any help will be accepted coordially... Here is the not working consumers.py from django.contrib.auth import get_user_model from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer import json from .models import Message User = get_user_model() class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): messages = Message.last_10_messages() content = { # 'command': 'messages', 'messages': self.messages_to_json(messages) } self.send_message(content) def new_message(self, data): author = data['from'] author_user = User.objects.filter(username=author)[0] message = Message.objects.create( author=author_user, content=data['message']) content = { 'command': 'new_message', 'message': self.message_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.message_to_json(message)) return … -
Django project needs to run with 3 major work concerns (scheduling processes, ansible jobs, and API server). But Nginx keeps killing my workers
I use a Django backend which has 2 main workloads: API server for the Angular UI Frontend and Django Admin Screens Scheduler, which kick off about 8 difference scheduled services Metric collection: API calls against a fleet of servers for regular status updates, then stores the responses in the PostgreSQL database. Runner: Runs Ansible jobs against our fleet of servers Everything is tied to the same PostgreSQL database and often crossed referenced. So don't think of these as logical different applications, it's not. The problem all stems around Gunicorn webserver and Timeouts. Gunicorn has 6 workers. With the default settings Gunicorn loves to kill processes that have not been used in the last ~30 seconds by default. Which works great if your workload is just HTTP calls and not background processes. But since I clearly have both I have issues with gunicorn killing or not killing my processes. I had the gunicorn timeout really high at 21600 secs(6 hours) for years. With this setting it would let my Ansible jobs finish and my scheduler jobs finish. But database would have a large number of inactive (2000~4000) and active (1~20) sessions. The database would be sluggish and connections would be slow … -
Error al hacer un proceso en manage.py Intel M1
Queria saber si me podias ayudar, la cuestión es que al momento de hacer un makemigrations en Django o Python me arroja este error y no he podido solucionarlo, y no he podido en si arrancar el servidor para trabajar, no se si les ha pasado algo parecido y me puedan decir que hacer, es en una MacBook M1 > "Traceback (most recent call last): File > "/Users/jesusochoagonzalez/Documents/GitHub/cip_django/manage.py", > line 22, in <module> > main() File "/Users/jesusochoagonzalez/Documents/GitHub/cip_django/manage.py", > line 18, in main > execute_from_command_line(sys.argv) File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/management/__init__.py", > line 401, in execute_from_command_line > utility.execute() File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/management/__init__.py", > line 395, in execute > self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/management/base.py", > line 330, in run_from_argv > self.execute(*args, **cmd_options) File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/management/base.py", > line 368, in execute > self.check() File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/management/base.py", > line 392, in check > all_issues = checks.run_checks( File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/checks/registry.py", > line 70, in run_checks > new_errors = check(app_configs=app_configs, databases=databases) File > "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/checks/urls.py", > line 13, in check_url_config > return check_resolver(resolver) File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/checks/urls.py", > line 23, in check_resolver > return check_method() File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/urls/resolvers.py", > line 408, in check > for pattern in self.url_patterns: File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/utils/functional.py", > line 48, in __get__ > res = instance.__dict__[self.name] = self.func(instance) File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/urls/resolvers.py", > line 589, in url_patterns > patterns = … -
Django shell bad scope for script files
Problem: Given the following python script script.py import time class Test: def __init__(self): print("time class", time) # In class scope def testing(): print("time method", time) # In method scope #Test() print("time top", time) # In file scope testing() When i try to execute this file in django's shell python3 manage.py shell < script.py I get the following error: time top <module 'time' (built-in)> Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/kailen/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/kailen/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/kailen/.local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/kailen/.local/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/kailen/.local/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 93, in handle exec(sys.stdin.read()) File "<string>", line 12, in <module> File "<string>", line 8, in testing NameError: name 'time' is not defined This same error will happen when using any imported function/class/module inside the scope of a method/class. I have tried asigning an alias, importing the whole module and importing only the required function, nothing seems to work. Context: I was trying to code a daemon for using selenium and some of my django's models, i ended up coding it as a class … -
Deploying python Django project to Heroku error: ModuleNotFoundError: No module named 'core'
I am attempting to deploy a django project to Heroku and I'm stumped with this error right at the bottom: 2022-03-04T03:32:53.360457+00:00 heroku[web.1]: Starting process with command `gunicorn --pythonpath backend.core backend.core.wsgi --log-file -` 2022-03-04T03:32:55.579764+00:00 heroku[web.1]: State changed from starting to crashed 2022-03-04T03:32:54.908542+00:00 app[web.1]: [2022-03-04 03:32:54 +0000] [4] [INFO] Starting gunicorn 20.1.0 2022-03-04T03:32:54.908855+00:00 app[web.1]: [2022-03-04 03:32:54 +0000] [4] [INFO] Listening at: http://0.0.0.0:39265 (4) 2022-03-04T03:32:54.908899+00:00 app[web.1]: [2022-03-04 03:32:54 +0000] [4] [INFO] Using worker: sync 2022-03-04T03:32:54.912389+00:00 app[web.1]: [2022-03-04 03:32:54 +0000] [9] [INFO] Booting worker with pid: 9 2022-03-04T03:32:54.974193+00:00 app[web.1]: [2022-03-04 03:32:54 +0000] [10] [INFO] Booting worker with pid: 10 2022-03-04T03:32:55.113641+00:00 app[web.1]: [2022-03-04 03:32:55 +0000] [9] [ERROR] Exception in worker process 2022-03-04T03:32:55.113643+00:00 app[web.1]: Traceback (most recent call last): 2022-03-04T03:32:55.113660+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-03-04T03:32:55.113661+00:00 app[web.1]: worker.init_process() 2022-03-04T03:32:55.113661+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-03-04T03:32:55.113661+00:00 app[web.1]: self.load_wsgi() 2022-03-04T03:32:55.113662+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-03-04T03:32:55.113662+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-03-04T03:32:55.113662+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-03-04T03:32:55.113663+00:00 app[web.1]: self.callable = self.load() 2022-03-04T03:32:55.113663+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-03-04T03:32:55.113663+00:00 app[web.1]: return self.load_wsgiapp() 2022-03-04T03:32:55.113663+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-03-04T03:32:55.113664+00:00 app[web.1]: return util.import_app(self.app_uri) 2022-03-04T03:32:55.113664+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/util.py", line 359, in import_app 2022-03-04T03:32:55.113664+00:00 app[web.1]: mod = importlib.import_module(module) 2022-03-04T03:32:55.113665+00:00 app[web.1]: … -
Is there anyway I can run colab notebook from my local computer?
I am writing my Django web application locally using VScode but as part of my work is done using deep learning to create 3D reconstruction for the face and can not be done locally because I need powerful gpu. What I am trying to do is connect a function to use this notebook... so can anyone tell me if It's applicable? -
django runserver failed but gunicorn works
I am refactoring my django app, but I find that if I import an unexisted module in my urls.py, I will fail when I run python manage.py runserver, but I can still succeed if I run the gunicorn xxx.wsgi:application, I feel sucked, can anyone tell me what happend? Here is the output of runserver: /home/qspace/mmpaytestWepayImageServer # python bin/manage.py runserver Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib64/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/urls/resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], … -
Persist Logged-out User's Session When User Logs In - Add-to-cart Scenario
I want to allow non-logged-in (anonymous) users to add items to their cart. The flow: Non-logged-in User loads homepage and clicks "products" link On "products" listview page, user clicks product to detail page On detail page, user clicks an Add-to-Cart button A Javascript fetch occurs to a Django view Distilled down "Add to cart" function: def add_to_cart(request): data = json.loads(request.body) request.session.create() if request.session.session_key is None else request.session.session_key cart, created = Cart.objects.get_or_create(session_key=request.session.session_key, user_id=request.user.id) product = get_add_to_cart_product() cart.products.add(product) response = { 'message': 'success', ... } return JsonResponse(response, status=200) add_to_cart just creates a session if none existed, uses session key in cart creation, and adds the product to the cart. User then goes to checkout page At this point, let's just say the session_key is 74hh8kte1hptt984so5fhl5vfzyq4unb User will need to login or create an account. This is where problems begin. Once user logs in, session_key changes to something else. I was using LoginView as seen below... My original urls.py: from django.urls import path from django.contrib.auth.views import LoginView, LogoutView from django.conf.global_settings import LOGOUT_REDIRECT_URL from .views import CustomLoginView app_name = 'accounts' urlpatterns = [ path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', LogoutView.as_view(), {'next_page': LOGOUT_REDIRECT_URL}, name='logout'), ] but request.session.flush() or request.session.cycle_key() essentially wipes out the previous session_key. These two … -
#DJANGO - I need to display two (or more) rows of a table in my view, currently I can only display one of the rows
Hello people I am working with ticket creation and there is a 1-N relationship, (a ticket can have multiple messages) I have a view that creates a ticket, in the creation process a message is added - All right here I have a view that adds a new message to the ticket(s), thus 'activating' the 1-N - All right here I have a ticket detail view view (code below) - Here starts my difficulty def ticket_by_id(request, ticket_id, message_id): mesTicket = MessageTicket.objects.get(pk=message_id) ticket = Ticket.objects.get(pk=ticket_id) return render(request, 'support/ticket_by_id.html', {'ticket': ticket, 'messageticket': mesTicket}) the code view above works when the ticket has only one message, but how can I display the multiple messages in this view? Sorry but it was inevitable to use images here For example in the image below there is my database, highlighting two lines that are linked to ticket 9 database, highlighted in ticket messages 9 Below is an image of my ticket detail view my detail view of the ticket How should I display in the view the two messages (or 3, or 4, anyway... more than one) that are related to the ticket, as I would show in my view (image 2) lines 9 and 12 … -
How to prefetch for individual object? (AttributeError: object has no attribute 'select_related')
How do I prefetch for a single object? I.e. select_related for a ForeignKey for one object: # models.py class Bar(models.Model): title = models.CharField() class Foo(models.Model): bar = models.ForeignKey(Bar) b1 = Bar.objects.create(title="Bar") f1 = Foo.objects.create(bar=b1) Foo.objects.all().first().select_related("bar") # AttributeError: 'Foo' object has no attribute 'select_related' -
How can I change my database from sqlite3 to mysql in Django
I've worked with mysql in my django project but in pycharm the default database is SQLite, i've created a MySQL database but I have a database connection problem (when I run makemigrations and migrate commands, everything runs successfully but the database is still empty!) so I guess if I could Change db.sqlite3 file to db.mysql maybe I can solve my problem settings.py and I don't know if db.sqlite3 file is normal to be like that or that's a problem db.sqlite3 but pressing "Reload in another encoding" may change the content of the file reload in another encoding -
CKEditor, Django and EasyPrint
I have an application that renders PDF files from a CKeditor content. I am having problems when rendering is generate because the text from CKeditor is rendered with the Default Font and Size, but not the style the user saved. I would to know how can I extract the style to applied to the template before rendering -
Can't use swagger in Django 4.0?
After installing Django 4.0 and configuring swagger, 'TypeError: 'set' object is not reversible' occurs. Is it possible that Django 4.0 can't use swagger? -
Django Account Verification Email Template shows HTML Code
I'm trying to test an email template for my Django Account Verification Email. But everytime I send the email instead of seeing the html page rendered properly with bootstrap the Email shows the HTML Code in plaintext, what can I do fix this? acc_verification_email.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> <div class="col d-flex justify-content-center w-40 h-100 bg-primary"> <div class="row"> Learning-Electronics </div> <div class="row"> <div class="col"> <div class="row"> Obrigado por te registares! </div> <div class="row"> Verifica o teu endereço de E-mail </div> </div> </div> <div class="row"> <p><h2>Olá {% autoescape off %} {{user.first_name}} {% endautoescape %}</h2></p> <p>Estás quase pronto para começar! Clica no botão abaixo para verificar o teu e-mail e desfrutares da nossa plataforma de aprendizagem</p> </div> <div class="row"> {% autoescape off %} <button type="button" class="btn btn-warning" href="http://{{ domain }}{% url 'account:activate' uidb64=uid token=token %}">VERFICA O EMAIL</button> {% endautoescape %} </div> <div class="row"> <p><h3>Obrigado,</h3></p> <p><h3>Da Equipa Learning-Electronics</h3></p> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> views.py ... (some code) current_site = get_current_site(request) mail_subject = 'Ativação de conta no Learning-Electronics' message = render_to_string('acc_active_email.html', { 'user': account, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(account.pk)), 'token': … -
Django logging errors into seperate files by timestamp
I have set up a Django log successfully with the following code: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': 'debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, }, } And from this, I'm able to find errors logged in the 'debug.log' file that's define above. However what I'd like to achieve is that any Django error is sent to an individual and timestamped log file. For example, if a ValueError is encountered, it would save it to a file named something like: debug_2022-03-04_1143.log I searched some other answers on this, but most seemed to be talking about timestamping at logged intervals, and I couldn't find a solution to the objective I listed above. Any help is appreciated. -
NamedTemporaryFile triggers SuspiciousFileOperation
In django version 3.2.12, I try to download an image for which I have an URL and store it inside an ImageField. It looks like this: def load_image_from_url(self): image_file = NamedTemporaryFile(delete=True, dir='project/media') with urlopen(self.extra_large_url) as uo: assert uo.status == 200 image_file.write(uo.read()) image_file.flush() image = File(image_file) self.image.save(image.name, image) When I create the NamedTemporaryFile, the path generated is an absolute path. In django.core.files.utils, it get blocked in this condition: if allow_relative_path: # Use PurePosixPath() because this branch is checked only in # FileField.generate_filename() where all file paths are expected to be # Unix style (with forward slashes). path = pathlib.PurePosixPath(name) if path.is_absolute() or '..' in path.parts: raise SuspiciousFileOperation( "Detected path traversal attempt in '%s'" % name ) With a dir argument set for the NamedTemporaryFile, the issue remains even if the folder is a subdirectory of the project. Is there a better solution than doing this: self.image.save(os.path.basename(image.name), image) -
Django serialization
serialization is not getting all values i have this object and and assign a property to it, but in a moment of serialization the value that i assign is not serialized @login_required(login_url='auth:login') def get_instance_provisioning(request): instance_pk = request.GET.get('instance_pk') viewpoints_list = CViewPoint.objects.filter(instance_id=instance_pk) five_mins = timedelta(minutes=5) ten_mins = timedelta(minutes=10) now_time = timezone.now() paginator = Paginator(viewpoints_list, 1) viewpoints = [] page = request.GET.get('page') try: viewpoints = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. viewpoints = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. viewpoints = paginator.page(paginator.num_pages) for viewpoint in viewpoints: # checkedIn info checked_in = PmsCheckin.objects.filter( cviewpoint=viewpoint).order_by('id') viewpoint.is_checkedin = "checked-in-status" if len( checked_in) > 0 else "checked-out-status" data = serialize("json", viewpoints) return JsonResponse(data) -
django use subquery to annotate count of distinct values of foreign key field
I am trying to annotate the quantity of distinct products but I have not been successful as of now. I get error such as: ProgrammingError: subquery must return only one column LINE 1: ..._id", "shop_selectedproduct"."create_date", COUNT((SELECT U0... I have the following models: class ShopItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) store = models.ForeignKey(to=Store, on_delete=models.CASCADE) name = models.CharField(max_length=250) class SelectedProduct(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="products", null=True, blank=True) product = models.ForeignKey(ShopItem, null=True, blank=True, on_delete=models.SET_NULL) class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name="orders") status = models.PositiveIntegerField(choices=OrderStatus.choices, default=OrderStatus.CART) number = models.CharField(max_length=36, blank=True, null=True) my attempt to count distinct shopitems such as p1, p2, p3, p4 and p5 where p1 quantity should be 3 because it is selected three times, whereas others may only have a quantity of one since we only selected one of each products. My attempt as of now is this: # order = 1 SelectedProduct.objects.filter(order=order).annotate(quantity=Count(Subquery(ShopItem.objects.filter(id=OuterRef("product"))))) is there anyway I could count how many times a product is selected and annotate that on the selected_product such as: p1.quanity > 3 p2.quanity > 3 p3.quanity > 3 p4.quanity > 1 p5.quanity > 1 I'd appreciate any insights. -
Understanding relationship direction of Model fields in Django
I have used Django for quite awhile but not sure I fully grasp how the relationships should work. this is best described in example so here goes. Let's assume there is a Company which has several Departments and each Department can have several Roles in it. Then, each Role can have several Employees. The questions come about how the fields should be laid out when it comes to accessing the data. Some of the questions that come up may seem obvious and may be better understood as I write them out but bare with me because I am using this to learn. Should it be: Example 1 (redundant): class Company(models.Model): name = charfield departments = m2m(Department) roles = m2m(Role) employees = m2m(Employee) class Department(models.Model): name = charfield roles = m2m(Role) employees = m2m(Employee) class Role(models.Model): name = charfield employees = m2m(Employee) class Employee(models.Model): name = charfield Example 2 (not redundant): class Company(models.Model): name = charfield departments = m2m(Department) class Department(models.Model): name = charfield roles = m2m(Role) class Role(models.Model): name = charfield employees = m2m(Employee) class Employee(models.Model): name = charfield Example 3 (fields look upwards): class Company(models.Model): name = charfield class Department(models.Model): name = charfield company = FK(Company) class Role(models.Model): name … -
Multiple IF statements in Django/Python
I was wondering if someone could help me out here, I'm struggling to group my IF statements together in such a way to achieve my results. I'm pretty new to python/django so any advice would be greatly appreciated. I'm trying to make a 'Like' and a 'Dislike' button for my webpage. I have it all set up and I can have each individual element working but I can't seem to group them. What I'm trying to say is this, this will allow me to 'like' my post: class PostLike(View): def post(self, request, slug, *args, **kwargs): post = get_object_or_404(Post, slug=slug) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) else: post.likes.add(request.user) return HttpResponseRedirect(reverse('image_details', args=[slug])) This will allow me to 'dislike' my post: class PostLike(View): def post(self, request, slug, *args, **kwargs): post = get_object_or_404(Post, slug=slug) if post.dislikes.filter(id=request.user.id).exists(): post.dislikes.remove(request.user) else: post.dislikes.add(request.user) return HttpResponseRedirect(reverse('image_details', args=[slug])) As you can see, my code is basically duplicated and they both work well individually, what I'm trying to do is combine them into one function where if I have already 'liked' my page, I can click the 'dislike' button to dislike my page and remove my 'like' Many thanks in advance! -
In django i runned migrations successfully but my database is still empty?
I worked in pycharm professional, I create my database and test it successfully database creation , I create my model in models.py and i runned makemigrations then migrate successfully running makemigrations then migrate and the new python file generated successfully 0001_initial.py but when i oppened my database it was empty! -
Django Rest Framework Analytics
I've been searching the internet for hours and can't find answer so this is my last resort. Do you guys have any idea what's the best way to capture how much a user has sent let's say get request for a specific endpoint? I also want it to be distinguishable by whether the user sent a request on a mobile app or on a website (the same endpoint). I thought about making a model something like: class Visit(models.Model) product = models.ForeignKey('Product') user = models.ForeignKey('User') on_mobile = models.BooleanField(default='False') on_website = models.BooleanField(default='False') times_visit = models.IntegerField(default=0) and shooting if Visit.objects.get(user=self.request.user, product=self.kwargs['pk']).exists(): times_visit += 1 Visit.objects.create(user=self.request.user, product=self.kwargs['pk']) Do you have any idea how "check" whether user sent it through mobile app or website? Or maybe there is some other better way? I would be thankful for any kind of help. -
render media file to html template from views.py django
I am trying to show image from views.py to jinga2 html template. Here is code models.py class SkinModel(models.Model): pic=models.ImageField(upload_to='images',blank=True) forms.py class SkinForm(forms.ModelForm): class Meta: model=SkinModel fields = "__all__" views.py def home(request): if request.method=='POST': form = SkinForm(request.POST,request.FILES) if form.is_valid(): img=form.cleaned_data['pic'] if img: fs = FileSystemStorage() filename = fs.save(img.name, img) path = fs.url(filename) print(path) return render(request,'home.html',{'form':form,'path':path}) home.html {% load static %} <img src="<img src="{{ path }}">" ,width="500" height="400"> the print statement shows the path like /media/bcc_38Mf6gh.jpg but i dont know how to render it on html template