Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
aws ssh server connect port 22: operation timed out
I am working on this tutorial (https://testdriven.io/blog/deploying-django-to-ecs-with-terraform/#nginx)and while I was following the steps, I tried to connect all of my instances via ssh by following these instructions (https://aws.amazon.com/blogs/compute/new-using-amazon-ec2-instance-connect-for-ssh-access-to-your-ec2-instances/). And by following the section where it starts by "connecting to an instance using EC2 Instance Connect", I typed in "$ aws ec2-instance-connect send-ssh-public-key --region us-east-1 --instance-id i-0989ec3292613a4f9 --availability-zone us-east-1f --instance-os-user ec2-user --ssh-public-key file://mynew_key.pub {" command on the terminal to push the public key to the instance using the send-ssh-public-key. After that, I tried to connect to the instance using the associated private key: $ ssh -I mynew_key ec2-user@ec2-34-204-200-76.compute-1.amazonaws.com". And it successfully worked out and I came to the end of the deploying Django tutorial. But when I was testing whether it properly connects to the server using the "http://(load balancer IP)" template, I kept getting a "503 service unavailable" error. So, I fixed the issue by changing the inbound rule sources to "0.0.0.0/0", but after that, it still gave me a "502 Bad Gateway" error. To find where the issue was happening, I checked whether the instances were connected properly and it gave me an error saying "ssh: connect to host xx port 22: Operation timed out". To resolve this, I … -
sqlite3 Database file is not visible in pycharm after migrate
enter image description herePycharm IDE is not generating database file I have followed all the commands correctly First I used -- > python manage.py makemigrations reels Yes it created a file like 0001_initial.py, After that I tried to migrate your text using ---> python manage.py migrate But the database file is not showing anything, I don't see anything there. Can someone please help me. -
How to create a mixin for `django_filters.FilterSet`?
I have a bunch of FilterSets to which I'd like to add the same new filters, but whenever I do something like below, I get an error saying that FilterSet.Meta must specify a model. E.G: class ModifiedAtMixin: modified_at_until = django_filters.DateTimeFilter(method="modified_until") def modified_until(self, queryset, name, value): return queryset.filter(modified_at__lte=value) class Meta: fields = ("modified_at_until",) class FooFilterSet(ModifiedAtMixin, django_filters.rest_framework.FilterSet): created_at_until = django_filters.DateTimeFilter(method="created_until") def created_until(self, queryset, name, value): return queryset.filter(created_at__lte=value) class Meta: model = Foo fields = ModifiedAtMixin.Meta.fields + ("created_at_until",) For reference, I also tried changing the order of parent classes in FooFilterSet and got nothing. How can I created a reusable mixin such as ModifiedAtMixin -
Editable frontend solution for a 2d array in a Django form
I am building a Django app, where a model "Foo" has a ManyToMany relation with "Bar" like this: Foo(Model): [field1] [field2] ... Bar(Model) [general_field1] [general_field2] ... FooBar(Model) ForeignKey(Foo) ForeignKey(Bar) [specific_field1] [specific_field2] ... The main model is Foo. I display each Foo in a template with it's fields and a 2D list of FooBars with general and specific fields (ordered list with several FooBars on each line). I need a solution to save this to the database (Problem 1) and more importantly to create a form or custom input fields for the user to populate it (Problem 2). The user should see (after the input fields for the Foo fields) some kind of blank list. There should be a search field with prerendered Bar models beneath it. As the user types in the search field the results beneath it are filtered. If the user selects a Bar a modal should open with fields to populate the "specific" fields for the actual FooBar (the general fields of the Bar are preset). After that the FooBar should appear in the list and the process continues. If the search result is blank (the user can't find the desired Foo) a "Create new Foo" option … -
Can not upload image
I try to upload an image in Django but I can't. I don't know what is the problem. The error: django.core.exceptions.SuspiciousFileOperation: Detected path traversal attempt in '/media/uploads/87176296b7b2425e81e266eaed65019b.png' Bad Request: /api/upload_file/ Bad Request: /api/upload_file/ [03/Aug/2023 17:47:52] "POST /api/upload_file/ HTTP/1.1" 400 17430 /api/upload_file: def upload_file(request): request_file = request.FILES['file'] if 'file' in request.FILES else None if request_file is None: data={ "error": "No file", } return Response(status=status.HTTP_400_BAD_REQUEST, data=data) if request_file.size > 20*1024*1024: data={ "error": "Image file too large (>20mb)", } return Response(status=status.HTTP_400_BAD_REQUEST, data=data) allowed_file_types = ['jpeg', 'jpg', 'png'] file_type = imghdr.what(request_file) if file_type not in allowed_file_types: data = { "error": "Invalid file type", } return Response(status=status.HTTP_400_BAD_REQUEST, data=data) upload = Upload(image=request_file) upload.save() data = { "upload_id": upload.id, } return Response(status=status.HTTP_200_OK, data=data) The Upload model: class Upload(models.Model): image = models.ImageField( verbose_name="Image", upload_to=path_and_rename_upload, ) patient = models.ForeignKey( "users.Patient", verbose_name="Patient", related_name="uploads", on_delete=models.SET_NULL, null=True, blank=True, ) upload_date = models.DateTimeField( verbose_name="Upload Date", auto_now_add=True, ) def __str__(self): return self.image.name @deconstructible class PathAndRename(object): def __init__(self, sub_path): self.path = sub_path def __call__(self, instance, filename) -> str: ext = filename.split(".")[-1] filename = f"{uuid4().hex}.{ext}".lower() return os.path.join(self.path, filename) path_and_rename_upload = PathAndRename("/media/uploads") I tried making the path BASE_DIR/self.path/filename but didn't make any differences. My settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] if not DEBUG: … -
Trying to make a Roster class out of a Player class (in Django), Help! This is for a class assignment
Working on my models.py for my Team manager app and I can't figure out how to layout my class for a roster. I am new to Django so any help is greatly appreciated. The idea is to have the players on the team but then having a roster to show who is playing which game. Here's what I have so far: class Player(models.Model): player_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=45) last_name = models.CharField(max_length=45) cap_number = models.CharField(max_length=45, blank=True, default='') def __str__(self): result = '' if self.cap_number == '': result = '%s, %s' % (self.last_name, self.first_name) else: result = '%s, %s (%s)' % (self.last_name, self.first_name, self.cap_number) return result class Meta: ordering = ['last_name', 'first_name', 'cap_number'] constraints = [ UniqueConstraint(fields=['last_name', 'first_name', 'cap_number'], name='unique_player') ] class Roster(models.Model): roster_id = models.AutoField(primary_key=True) roster_name = models.CharField(max_length=45) player = models.ManyToManyField(Player) def __str__(self, data=None): return f'{self.roster_name} - {self.player}' class Meta: ordering = ['roster_name', 'player'] And this is the error I get when I try to run makemigrations: ERRORS: organizer.Roster: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'player'. Do I have to make another class to put the players into a list? -
Is python zipfile save to aws s3 bucket
Is anyone know that the location of zipfile created in python can be changed to aws s3 bucket? For now, my zipfile is created in my root folder. I know that I can add the directory path to the begin of the file name to change the create location, but how about s3 bucket? -
i am getting following error when i tried to create a django project ? i am using python 3.11 with pip 23.2.1 ? Any help is appreciated
i am trying to create a django project but i am not able to create it. $ django-admin startproject web Fatal error in launcher: Unable to create process using '"C:\Users\laupha\AppData\Local\Programs\Python\Python311\python.exe" "C:\Users\laupha\AppData\Local\Programs\Python\Python311\Scripts\django-admin.exe" startproject web': The system cannot find the file specified. -
AttributeError: 'Command' object has no attribute 'scriptable'
After updating Django 3->4.2.4 One of my UpdateView shows 'SomeModel' instance needs to have a primary key value before this relationship can be used. I think there could be some model need migrate ./manage.py makemigrations --dry-run File "/Users/user/Git/erp/venv/lib/python3.11/site-packages/django/core/management/commands/makemigrations.py", line 99, in log_output return self.stderr if self.scriptable else self.stdout ^^^^^^^^^^^^^^^ AttributeError: 'Command' object has no attribute 'scriptable' -
TypeError at / Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x0000025FE3733310>>
Im trying to make my openai chatbot save chats for the user that is making them, but it is giving me this error: Traceback (most recent call last): File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\fields\__init__.py", line 2053, in get_prep_value return int(value) ^^^^^^^^^^ TypeError: int() argument must be a string, a bytes-like object or a real number, not 'SimpleLazyObject' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\Downloads\finalproject\finalproject\django_chatbot\chatbot\views.py", line 29, in chatbot chats = Chat.objects.filter(user=request.user) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 1436, in filter return self._filter_or_exclude(False, args, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 1454, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 1461, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\query.py", line 1534, in add_q clause, _ = self._add_q(q_object, self.used_aliases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\query.py", line 1565, in _add_q child_clause, needed_inner = self.build_filter( ^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\query.py", line 1480, in build_filter condition = self.build_lookup(lookups, col, value) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan A\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\sql\query.py", line 1307, in build_lookup lookup = lookup_class(lhs, rhs) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Nathan … -
How to solve error while running pip install mysql on MAC( Exception: Can not find valid pkg-config name)
Already tried re-installing everything. still got this message /bin/sh: pkg-config: command not found /bin/sh: pkg-config: command not found Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 127. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 127. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in main() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) ^^^^^^^^^^^^^^^^^^^^^ File "/private/var/folders/sl/r5ldvvwx13qbfft41c70zmy80000gn/T/pip-build-env-sflnewt3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 341, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/private/var/folders/sl/r5ldvvwx13qbfft41c70zmy80000gn/T/pip-build-env-sflnewt3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 323, in _get_build_requires self.run_setup() File "/private/var/folders/sl/r5ldvvwx13qbfft41c70zmy80000gn/T/pip-build-env-sflnewt3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 338, in run_setup exec(code, locals()) File "", line 154, in File "", line 48, in get_config_posix File "", line 27, in find_package_name Exception: Can not find valid pkg-config name. Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> See above for output. note: This error originates from a subprocess, and is likely not a problem with pip. -
Django constraint for "field one not in field two for any row"?
Suppose I have a Django model with two fields one and two: class MyModel(models.Model): one = models.CharField(max_length=100, unique=True) two = models.CharField(max_length=100) unique=True means if I try to put in a row with one="one" when another such row already exists, a unique constraint will be violated. How would I make a Django constraint that says if there is a row with one="one", then I can't put in a row with two="one"? This does seem related to this question and this answer, but I don't quite see the answer to my question. -
How to override the templates of `django-two-factor-auth` for Django Admin?
I'm trying to override the templates of django-two-factor-auth for Django Admin but I don't know how to do it. *I don't have frontend with Django. Instead, I have frontend with Next.js and backend with Django. This is my django project: django-project |-core | |-settings.py | └-urls.py |-my_app1 | |-models.py | |-admin.py | └-urls.py └-templates And, how I set django-two-factor-auth following the doc is first, I installed django-two-factor-auth[phonenumbers]: pip install django-two-factor-auth[phonenumbers] Then, set these apps below to INSTALLED_APPS, OTPMiddleware to MIDDLEWARE, LOGIN_URL and LOGIN_REDIRECT_URL in core/settings.py as shown below: # "core/settings.py" INSTALLED_APPS = [ ... 'django_otp', # Here 'django_otp.plugins.otp_static', # Here 'django_otp.plugins.otp_totp', # Here 'two_factor' # Here ] ... MIDDLEWARE = [ ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', # Here ... ] LOGIN_URL = 'two_factor:login' # Here # this one is optional LOGIN_REDIRECT_URL = 'two_factor:profile' # Here ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'templates', ], ... }, ] Then, set the path below to core/urls.py: # "core/urls.py" ... from two_factor.urls import urlpatterns as tf_urls urlpatterns = [ ... path('', include(tf_urls)) # Here ] Finally, migrate: python manage.py migrate And, this is Login page: http://localhost:8000/account/login/ My questions: How can I override the templates of django-two-factor-auth for Django Admin? Are there … -
Setting local time and date conversion in Python
I run the following code on the system and server and get different results How to set the time zone to get the same result regardless of the system or server settings print(datetime(2023,6,6,0,0).timestamp()) -
Steam OpenID dj-rest-auth dont return access token
urls.py from django.contrib import admin from django.urls import path, include, re_path from rest_framework.routers import SimpleRouter from store.views import CaseViewSet, auth, GoogleLogin, VkLogin from .settings import STEAM_CALLBACK_URL from allauth.socialaccount.providers.steam.views import SteamOpenIDLoginView import allauth router = SimpleRouter() router.register(r"case", CaseViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('auth/google/', GoogleLogin.as_view(), name='google_login'), path("auth/vk", VkLogin.as_view(), name = "vk_login"),\ path("auth/steam", SteamOpenIDLoginView.as_view(), name = "steam_login"), path('auth/steamcallback', allauth.socialaccount.providers.steam.views.SteamOpenIDCallbackView.as_view(), name = STEAM_CALLBACK_URL), ] urlpatterns += router.urls in this code i create 2 endpoints. I open page and login with steam openid and it return dont JWT . -
SMTPServerDisconnected in Google App Engine Standard (but it works in Flexible)
I am trying to switch my Django (Python) app from from GAE Flexible environment to Standard. Everything works fine except sending emails via gmail SMTP. It works with a version in flexible env, but it doesnt work in the same code with standard. my app.yaml file includes inbound_services: - mail - mail_bounce My settings is: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-relay.gmail.com' EMAIL_HOST_USER = 'hidden@hidden.com' EMAIL_HOST_PASSWORD = 'hidden' DEFAULT_FROM_EMAIL = 'hidden@hidden.com' SERVER_EMAIL = 'hidden@hidden.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True The strange thing is that SMTP and the same email work fine in my other project with GAE standard with the same settings. -
Django i18n cannot use translated text in a dict
I am unable to store the translated texts in a dict class TestAPIView(APIView): def get(self, request): return Response({'msg': _("My error msg")}) The code above works. However when I tried to put the text into a dict. msg = { 123 : _("My error msg") } class TestAPIView(APIView): def get(self, request): return Response({'msg': msg[123]}) This doesn't translated the text. I have tried rerunning the makemessages and compilemessages, but it doesn't help. Any help? -
im trying to test this but it dont work pls help in django python
i dont know how to test this, pls can you guys find a way to test this i dont get it and i dont find videos on youtube aswell.I'm pretty new to this and so stressed because im so bad at programming right now. @login_required def update_billing_information(request: HttpRequest) -> HttpResponse: user = User.objects.get(pk=request.user.pk) form = BillingForm(instance=user) if request.method == "POST": form = BillingForm(instance=user, data=request.POST) if form.is_valid(): user = form.save() return redirect('show_billing_information') ctx = {"form": form} return render(request, "customer/_billing_edit.html", ctx) @login_required def show_billing_information(request: HttpRequest) -> HttpResponse: user = User.objects.get(pk=request.user.pk) ctx = {"user": user} return render(request, "customer/_billing_show.html", ctx) and chatgpt gave me this shit User = get_user_model() class BillingInformationTestCase(test.TestCase): def setUp(self): self.user = User.objects.create_user(email='Testuser32@gmail.com', password='testpassword', dob = date(1990, 1, 1)) self.factory = test.RequestFactory() self.client = Client() self.client.force_login(self.user) def test_update_billing_information_valid_form(self): request = self.factory.post('/update_billing_information/') request.user = self.user form_data = { 'billing_info': 'Updated Billing Info', "first_name" : 'Tim', "last_name" : 'Herb', "address1" : '123 Main Street', "address2" : 'Apt 2B', "city" : 'New York', "state" : 'Ny', "zip" : '12345', } request.POST = form_data response = update_billing_information(request) self.assertIsInstance(response, HttpResponseRedirect) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, '/views/customer/billing') def test_update_billing_information_invalid_form(self): request = self.factory.post('/update_billing_information/') request.user = self.user form_data = { 'billing_info': 'Updated Billing Info', "first_name" : '', "last_name" : '', "address1" … -
mod_wsgi with two python versions
I have an Ubuntu-18.04 LTS EC2 serving a django application with mysql Ver 8.0.16, Apache/2.4.29 and mod_wsgi/4.6.5complied withpython3.6. Now, I am targeting to deploy a new django application in the same Ubuntu EC2 serve and it requires python3.11+ virtualenv for installing its requirements.txt, now i am facing issues while deploying the new application. here are few other informations, Using Pyenv for creating virtualenvs, mod_wsgi is installed from source and compiled using ./configure --with-python=/home/ubuntu/.pyenv/shims/python3.6 after deploying the new django application the domain returns 500 error and logs are as follows api.log [03/Aug/2023:18:42:14 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:17 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:17 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:17 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:18 +0000] "GET / HTTP/1.1" 500 816 [03/Aug/2023:18:43:18 +0000] "GET / HTTP/1.1" 500 816 api_error.log [Thu Aug 03 18:43:18.047679 2023] [wsgi:error] [pid 170353:tid 140404074731072] mod_wsgi (pid=170353): Failed to exec Python script file '/var/www/project/newdjango/wsgi.py'. [Thu Aug 03 18:43:18.047724 2023] [wsgi:error] [pid 170353:tid 140404074731072] mod_wsgi (pid=170353): Exception occurred processing WSGI script '/var/www/project/newdjango/wsgi.py'. [Thu Aug 03 18:43:18.047795 2023] [wsgi:error] [pid 170353:tid 140404074731072] Traceback (most recent call last): [Thu Aug 03 18:43:18.047810 2023] [wsgi:error] [pid 170353:tid 140404074731072] File "/var/www/project/newdjango/wsgi.py", line 12, in <module> [Thu Aug 03 … -
Pycharm is not allowing me to make a password for a super user on my Django project
I am trying to create a superuser on the terminal on pycharm but It's not typing anyting when I try to create a password for that superuser in the terminal. I tried to recall the command "python manage.py createsuperuser" a few times but I still ran into the same issue. I was expecting it to type in the password, but no matter what I type it's not typing anything. I am following this tutorial: Python Tutorial-Python Full Course For Beginners and my issue is at 5 hrs and 38 mins. I am able to type in the username and email, but just not the password. -
Overlay search results from one div onto the one below
I created a search bar that shows results as a list. Initially, the results of the search bar would push the rows below it down to create space. I want it to overlay on top of the divs below it, but it cuts off and will not show the full list of results. I have tried changing z-index and using overlay: auto and position: absolute to no avail. Here are images of what I mean: Here is the code to set up the divs and rows in the form. Note: every field is its own search bar. <form id="part-data-form" name="part-data-form" method="post" class="d-flex flex-column" style="min-width: 0; min-height: 0"> {% csrf_token %} <div class="d-flex flex-grow-1 flex-column p-3 border border-secondary rounded m-2" style="overflow: auto; min-width: 0; min-height: 0"> <div class="row"> {% for field in form %} <div class="col-4 form-group"> <label class="fw-bold" for="{{ field.auto_id }}" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{{ field.field.tooltip|default:field.label }}"> {{ field.label }} {% if field.field.required %}<span class="text-danger">*</span>{% endif %} </label> {% if field.label == 'NHA Override' %} {{ field }} <div id="results"></div> {% else %} {{ field }} {% endif %} {% endif %} -
Django - best way to set up models for timeclock app?
I am working on an employee timeclock app in Django mostly as a test project. I am a newbie and I am not sure how best to set up the models, etc. I could create clockin and clockout models and reference the user as a foreign key. However then I am not sure the best way to calculate time between multiple clock-in and clock-out events in one day. Any ideas about the best way to handle this most efficiently? Thank you for any suggestions. -
How to reference newrelic keys via settings.py
I am just using NewRelic for the first time. I have the new relic.ini file, which includes the license_key and app_name hard coded, in my Django Python repository and have updated my manage.py script to be as so: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import newrelic.agent newrelic.agent.initialize('newrelic.ini') import os import sys def main(): ..... if __name__ == '__main__': main() When I run my api locally via ./manage.py runserver I can see the logs being tracked in NewRelic which is good. However, I'm wanting to remove the hardcoded license_key and app_name from the newrelic.ini file so that I can reference environment variables. I have read this documentation https://docs.newrelic.com/docs/apm/agents/python-agent/configuration/python-agent-configuration/#server-side-configuration which outlines the environment and config variables. I added this to my settings.py file so that I can override the env variables on deployment: NEW_RELIC_APP_NAME = "My API" NEW_RELIC_LICENSE_KEY="XXXXXXXXXXXXXXXX" I have tried removing license_key and app_name entirely from newrelic.ini keeping the variables but setting them equal to "" keeping the variables but setting license_key = NEW_RELIC_LICENSE_KEY but I can't seem to get it tracking without it being hardcoded in the newrelic.ini file So my question - how can I use environment variables with the newrelic.ini file? thanks in advance -
Using Python to Pull Data from XLSX file stored online
I'm building an app using Django that needs to be able to pull data from sheets stored in an XLSX file. For testing I've used files stored locally, but now that I need to put it online I need to be able to work with files stored online. I've tried working with files stored on SharePoint but haven't been able to work with the raw file. Is there a place these files could be stored where I can access them with Python or a way to make them accessible if stored somewhere like SharePoint? I also have to work with CSV files stored online but was able to do so by adding them to GitHub and accessing the raw file as shown in the image below. Is this possible anywhere for non CSV excel files? -
Django - limit_choices_to users within a group model
I have a group models with members and one admin which looks like this: class Group(models.Model): name = models.CharField(unique=True, max_length=255) members = models.ManyToManyField(User, related_name='members') is_admin = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, limit_choices_to={'members': True}) I want to show only members which are part of the group to the is_admin field. I tried the limit_choices_to method and referred the members but it is not working when I try to display the users in a form like this: form = EditGroupForm(instance=group). How can I do so?