Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Failed to load css
I have installed Geonode ( geospatial content management system), which is available on URL armsis.cas.am. It worked fine, but now there is a problem with CSS. I get an error GET http://armsis.cas.am/static/geonode/css/base.css net::ERR_ABORTED 403 (Forbidden) I thought the problem was in the path to static folder, but I get images from the same folder. Any ideas? ('m not a programmer, but I have some skills in Python/Web) -
Django verbose_name of reverse relation
I have a model like: class Question(models.Model): ... class Answer(models.Model): question = models.ForeignKey( Question, null=False, blank=False, on_delete=models.CASCADE, related_name='answers', verbose_name='translated name' ) I would now like to use the verbose_name in a template (as it is translated) over the reverse relation like {{ question.answers.verbose_name }}. Unfortunately this does not work. On the other hand {{ question.answers.related_name }} works. So it seems that in the reverse_relation only the related_name is available. Is there any way to get the verbose_name from the reverse relation? -
.mp4 file is not playing in Django template and FireFox or Chrome
I can save live RTSP video stream in .mp4 but when I run saved .mp4 video in Django template or Firefox or Chrome browser or VLC, video is not playing in ubuntu. I think I have a compatible issue problem in .mp4. Furthermore, I want to show and play .mp4 saved file in Django. I have a two IP camera which provides a live RTSP video stream. self.input_stream---> rtsp://admin:Admin123@192.168.1.208/user=admin_password=Admin123_channel=0channel_number_stream=0.sdp self.input_stream---> rtsp://Admin:@192.168.1.209/user=Admin_password=_channel=0channel_number_stream=0.sdp Python 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] on linux, Django==3.1.2 I am implementing this code in difference Ubuntu PCs Ubuntu = 18.04 and 20.04 opencv-contrib-python==4.4.0.46 opencv-python==4.4.0.46 ffmpeg version 4.2.4-1ubuntu0.1 Copyright (c) 2000-2020 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-10ubuntu2) I had tried different fourcc to save .mp4 but below fourcc work perfectly in Ubuntu. fourcc = cv2.VideoWriter_fourcc(*'mp4v') class ffmpegStratStreaming(threading.Thread): def __init__(self, input_stream=None, output_stream=None, camera=None, *args, **kwargs): self.input_stream = input_stream self.output_stream = output_stream self.camera = camera super().__init__(*args, **kwargs) def run(self): try:vs = cv2.VideoCapture(self.input_stream) fps_rate = int(vs.get(cv2.CAP_PROP_FPS)) ############################## ############################## # ~ print('fps rate-->', fps_rate,'camera id-->' ,str(self.camera.id)) # ~ vs.set(cv2.CAP_PROP_POS_FRAMES,50) #Set the frame number to be obtained # ~ print('fps rate-->', fps_rate,'camera id-->' ,str(self.camera.id),' ####### ') # initialize the video writer (we'll instantiate later if need be) writer … -
Different CMDs - difference for Python
I am a Windows10 user learning Django. And I am trying to run a server on my local device. While using the PyCharm command prompt, I constanly got some errors. A previous one, for example, was caused by SSLError (error was fixed thanks to Stackoverflow answers). Currently while doing the "runserver" command I am getting a new error: ImportError: DLL load failed while importing _sqlite3: module not found. At the same time there were and there still are absolutely no errors shown while using same django commands, but in Anaconda prompt. Why is that so? What's the difference between prompts? How to make the PyCharm command prompt work normally? "Anaconda3", "Anaconda3\scripts" and "Anaconda3\Library\bin" have been added to my PATH already. (According to answers found among Stakoveerflow, adding them is the number one solution / advice). Thank you! -
how to handle multiple keyword parameters in Django RestFramework URL
this my current url url("sample/userid",views.sample) I can query the data by userid or postid or x, or y parameters. how to handle this efficiently in a single url In the views, I will use kwargs to get the keywords, but not sure how to handle it in the url. -
Django ORM update field to NOW() returning 0 error
I am trying to loop through a list of results, process them, then update their "updated_details" field. users_to_update = TiktokUser.objects.filter(Q(updated_details__lt=datetime.utcnow() - timedelta(weeks=1)) | Q(updated_details__isnull=True))[0:1] for user_to_update in users_to_update: print(datetime.now()) user_to_update.updated_details = datetime.now() user_to_update.save() The idea being that on each loop, i set the updated_details to the current timestamp. My print() statement here correctly prints out the current date and time, however when I update the record itself and save, I get the following error: ['“0000-00-00 00:00:00.000000” value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) but it is an invalid date/time.'] Which implies to me it is attempting to set it to 0. My model definition is: class User(models.Model): ... updated_details = models.DateTimeField(blank=True, null=True) ... How do I get Django to set the field to the current DateTime? -
Djnago background task function not excecuting
I am using Django background task in my project. pip install django-background-task and Django background task is started by cron-jobs But background task function is not executing all the time.. in the database entry is automatically generating in background_task and background_task_completedtask table. but my functionality is not executing. could any one check ? I am stuck here and not able to do other data. my code is showing below views.py @api_view(['DELETE']) @permission_classes([IsAuthenticated]) def remove_finger(request): try: validation_msg = '' employee = Employee.objects.get(pk=request.query_params.get("EmployeeId")) finger_data = FingerPrintInfo.objects.filter(Activation=request.query_params.get("FingerId"), Employee=request.query_params.get("EmployeeId")) if not finger_data: validation_msg = validation["FDP7"] if validation_msg != '': return Response({msg: validation_msg}, status=status.HTTP_400_BAD_REQUEST) else: fing = finger_data.order_by('FingerPrintId') fingerId = fing[3].FingerPrintId finger_data.delete() FingerPrintActivation.objects.filter(pk=request.query_params.get("FingerId")).update( ActivationStatus=progress_msg["removed"], ActivationMessage=validation["FDP31"], ModifiedDate=date.today(), ModifiedUser=request.user.id ) remove_fingerprint(request.query_params.get("EmployeeId"), fingerId) return Response({msg: successMsg}, status=status.HTTP_200_OK) my tasks.py @background(schedule=django.utils.timezone.now()) def remove_fingerprint(empId, fingerId): """ Remove FingerPrint data from all Device Parameters: EmployeeId: FingerPrint Data Returns: Background Process Execute """ try: json_input = { "EmployeeID": empId, "FingerPrintID": fingerId } employee = Employee.objects.get(EmployeeId=empId) if employee.Security == static_values["const1"]: emp_device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"])) else: emp_device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"]), DefaultAccess=True) for div in emp_device: try: url = "http://"+ div.DeviceCode + "/DeleteFingerprint" resp = requests.post(url, json=json_input) if not resp.text.__contains__('200'): logging.getLogger("info_logger").info("Fingerprint not removed from in " + div.DeviceCode) except Exception as ex: logging.getLogger("info_logger").info("Fingerprint not removed from in … -
Update specific ORM object with self object attribute from filtered queryset
I'm wondering is there any option to update current ORM object from filtered queryset with a new value which comes from current object? Seems bit complicated so maybe I show you an example: Model looks like: class Car(models.Model): car_id = models.CharField(max_length=100) initial_value = models.IntegerField(null=True) end_value = models.IntegerField(null=True) And some cars in my DB have initial_value but doesn't have an end value, and I want to copy/update the initial_value from specific object to end_value, where end_value is None: And I know that there exists an ORM formula which update my object with given value in queryset: Car.objects.filter(end_value__isnull=True).update(end_value=100000) But I cannot pass object initial_value to end_value in update method Car.objects.filter(end_value__isnull=True).update(end_value=initial_value) <-- Error Please help, how can I pass object attribute to update attribute? Maybe there is different approach? -
django admin sort calculated fields in listview
I have two models, one (Device) which has a foreign key to the other (Storage). In the admin overview of Storage I wanna be able to add a count of how many Device has pointed to each Storage. Using the code below I'm able to correctly count the number of Devices pointing to each Storage. However, when trying to sort by the number in storage it crashes with the following error. Cannot resolve keyword '_get_device_number' into field. Choices are: ... #List of fields So my question is, how do I add my calculated field into the list allowed searches. class Device(models.Model): ... storage_id = models.ForeignKey(Storage, on_delete=models.PROTECT, blank=True,null=True) #Allowed to be null since a Device may not be in storage. class Storage(models.Model): ... def _get_device_number(self,): return Device.objects.filter(storage_id=self.storage_id).count() class StorageAdmin(admin.ModelAdmin): ... list_display = ['str', 'get_device_number',] def get_device_number(self, obj): return obj._get_device_number() get_device_number.admin_order_field = '_get_device_number' -
Change default port for django swagger-ui
I want to change the default port of swagger-ui to 8080 but my main Django API should listen on a different port. I have tried this in setting.py : SWAGGER_SETTINGS = { "base_path": 'localhost:8080/', } But still, the port of swagger-ui is not changed. I have also added this schema in urls.py of my project. # schema for swagger view schema_view = get_schema_view( openapi.Info( title="XMeme API", default_version='v1', description="Meme Stream", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="sonirudrakshi99@gmail.com"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), path('', include('my_api.urls')), path('swagger-ui/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), # Included another URLconf of swagger api ] -
Use Django REST framework serializer to save JSON requests to database
I'm absolutely new to Django and for some reason, I had to jump right to Django REST framework. I want to save JSON objects sent as POST requests in my database. The JSON object looks like this: [{ "title": "Bitcoin Price Likely to Reach $50K Soon According to This Indicator", "description": "", "date": "2021-02-09T09:08:58Z", "link": "https://cryptopotato.com/bitcoin-price-likely-to-reach-50k-soon-according-to-this-indicator/", "keywords": [{ "name": "bitcoin" }], "source": "https://cryptocompare.com" }, { "title": "Post-Tesla News FOMO Helps Bitcoin Price to Surge Above $48,000", "description": "", "date": "2021-02-09T09:08:58Z", "link": "https://www.cryptoglobe.com/latest/2021/02/post-tesla-news-fomo-helps-bitcoin-price-to-surge-above-48000/", "keywords": [{ "name": "bitcoin" }], "source": "https://cryptocompare.com" }] I created my models like this: class Keywords(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class News(models.Model): title = models.CharField(max_length=100) description = models.TextField() date = models.DateTimeField() link = models.URLField() keywords = models.ManyToManyField(Keywords) source = models.CharField(max_length=30) class Meta: db_table = "News" # ordering = "-date" def __str__(self): return self.title serializers: class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keywords fields = ["name"] class NewsSerializer(serializers.ModelSerializer): keywords = KeywordSerializer(read_only=True, many=True) class Meta: model = News fields = ["title", "description", "date", "link", "keywords", "source"] and finally my view: class NewsView(APIView): def post(self, request): news_serializer = NewsSerializer(data=request.data, many=True) try: if news_serializer.is_valid(): news_serializer.save() return Response("Created successfully", status=status.HTTP_201_CREATED) except Exception as e: print(e) return Response("Error, Don't know what", status=status.HTTP_400_BAD_REQUEST) … -
making a top navigation bar along with a side navigation bar in html(django)
Here's the body of my layout html page: <body> <!-- navbar --> <header> <nav class="navbar navbar-expand-lg navbar-light fixed-top navbar-custom trans"> <div class="container-fluid"> <a href="#" class="navbar-brand"> <!-- <img src="static/events/iiitu.png" alt="logo" class="d-inline-block align-middle mr-2 py-3"> --> <img src="" alt="logo" class="d-inline-block align-middle mr-2 py-3"> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse myNav" id="navbarNavDropdown"> <ul class="navbar-nav ms-auto"> <li class="nav-item"> <a style="color: black;" class="nav-link" aria-current="page" href="{% url 'events:home' %}">Home </a> </li> <li class="nav-item"> <a style="color: black;"class="nav-link active" href="#"> About Us </a> </li> <li class="nav-item dropdown"> <a style="color: black;" class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> User </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> {% if not user.is_authenticated %} <li><a class="dropdown-item" href="{% url 'events:register' %}">Register</a></li> <li><a class="dropdown-item" href="{% url 'events:login' %}">Login</a></li> {% endif %} <!-- <li><hr class="dropdown-divider"></li> --> {% if user.is_authenticated %} <li><a class="dropdown-item" href="{% url 'events:post_create' %}">Share Something</a></li> <li><a class="dropdown-item" href="{% url 'events:logout' %}">Logout</a></li> {% endif %} </ul> </li> <li class="nav-item"> <a style="color: black;" class="nav-link" href="#"> Contact Us </a> </li> </ul> </div> </div> </nav> </header> {% block content %} {% endblock %} {% block body %} {% endblock %} {% block script %} {% endblock %} Now, what i am unable to understand is: Where should i keep the … -
Django ORM: Order by dates and weekdays
I have a table that stores courses and one that stores their dates and weekdays: Course: ID, CourseDates (M2M) CourseDate: ID, Date (Date), Weekday (0-6), Full (Boolean) If its a date, weekday is NULL If its a weekday, date is NULL Only dates can be set to full (full=True) Use case: I want to order by the next occurence (date or weekday) that is not full. Challenge: Weekdays should only be considered if there is no date that is full for that day. Example: Course 1 1, Date=2021-02-12, Weekday=NULL, Full=True 2, Date=NULL, Weekday=4 (Friday), Full=False Course 2 3, Date=2021-02-13, Weekday=NULL, Full=False Expected Result: Course 2 Course 1 Explanation: Next date for Course 2: 2021-02-13 Next date for Course 1: 2021-02-19 (because 2021-02-12 is full) Question: Can this be done using SQL/Django ORM only? Does it even make sense? My current attempt (this wont work in the above example): """ The subquery annotates all CourseDates with the difference to today, orders them by days left, and in the main query we only use the first entry, which is the closest CourseDate for this course """ subquery = ( CourseDate .objects .exclude(full=True) .filter(course=OuterRef('id')) .filter(Q(date__gt=today_date) | Q(date__isnull=True)) .annotate(today=Value(today_date, output_field=DateField())) .annotate( days_until_next=Case( When(weekday__lt=today_weekday, then=6 … -
how to copy the tables of influx db ( free versione ) into postgres
project-schema As you see in the pictures I have this kind of schema, I'll have many "measurements" (tables) into influxdb, that I need to copy into Postgresdb, so my django app will query the local copy instead of influxdb. i really don't know how to start, I found a lot of mirroring setup for sql-sql db , but I don't find nothing for "timeserie db" and "relational db" -
Only allow a certain domain to access my Django backend
I'm currently developing an application which consists of a React frontend, which makes frequent requests to a Django backend. Both the React and Django applications are running on the same server. My problem is I wish to hide my Django backend from the world, so it only accepts requests from my React application. To do so, I've been trying several configurations of ALLOWED_HOSTS in my Django settings.py, but so far none of them seem to be successful. An example route that I wish to hide is the following: https://api.jobot.es/auth/user/1 At first I tried the following configuration: ALLOWED_HOSTS=['jobot.es'] but while this hid the Django backend from the world, it also blocked the petitions coming from the React app (at jobot.es). Changing the configuration to: ALLOWED_HOSTS=['127.0.0.1'] enabled my React app to access the backend but so could do the rest of the world. When the Django backend is inaccessible from the outside world, a get request from https://api.jobot.es/auth/user/1 should return a 400 "Bad Request" status. The error I get when the React app fails to request data from the Django backend is the following: Access to XMLHttpRequest at 'https://api.jobot.es/auth/login' from origin 'https://jobot.es' has been blocked by CORS policy: Response to preflight request … -
What is Causing Encrypted Nginx Log Lines and ERR_SSL_PROTOCOL_ERROR in Docker Compose?
I am running three docker containers in a django production environment on a google cloud VM with firewall settings open to https traffic. I am using a chained cert that I obtained from godaddy and concatenated the certs as per nginx docs. My containers are a django app, postgres, and nginx acting as a proxy in order to serve static files. I am orchestrating them using docker-compose. I also have a public URL pointing to the public IP of the google vm. When going to the endpoint in a browser I get an "ERR_SSL_PROTOCOL_ERROR" If I tail the nginx logs on the vm I get encoded log lines, like: nginx_1 | 93.173.8.110 - - [09/Feb/2021:09:02:12 +0000] "\x16\x03\x01\x02\x00\x01\x00\x01\xFC\x03\x03C\x08!\xB3d\xC76P\xE5\x I confirmed that the nginx container is up and running and started with no errors. Is there something obvious I am doing wrong? And specifically a reason my nginx log entries are encrypted and non-readable? Here is the Dockerfile: ########### # BUILDER # # First build step in order to make final image smaller. # This is referenced in second build step. ########### # pull official base image FROM python:3.8.3-alpine as builder # set work directory #WORKDIR /usr/src/app WORKDIR /code # set environment … -
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Django
I'm getting this error whenever I'm trying to run python manage.py runserver in Django. The error: django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Why can that be? I think it is because my settings.py it is called base.py instead of settings.py and that's why Django doesn't detect that file as my settings file. If that's the case, how can I assign the settigns file to that base.py fiile? this is the base.py file: import os from pathlib import Path from django.urls import reverse_lazy # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ######################################## # APPS ######################################## INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', 'allauth', 'allauth.account', 'djstripe', 'captcha', 'users', ] ######################################## # MIDDLEWARE ######################################## MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ######################################## # SECURITY ######################################## SECRET_KEY = os.environ.get("SECRET_KEY") DEBUG = bool(os.getenv("DJANGO_DEBUG", "False").lower() in ["true", "1"]) ALLOWED_HOSTS = [] ######################################## # OTHER ######################################## ROOT_URLCONF = 'urls' WSGI_APPLICATION = 'wsgi.application' SITE_ID = 1 ######################################## # TEMPLATES ######################################## TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates", ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
Insert database table name in raw sql in Django
I'm trying to pass the database table name into my raw sql query in Django like this: instance = Nutrient.objects.raw( ''' select * from %(table)s # <-- error here for system_time as of timestamp %(time)s where id=%(id)s; ''', params={'table': self.dbTable, 'time': timestamp, 'id': instance.id})[0] It works fine when I insert the timestamp or the instance id but it gives me an error on the table name: Error: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/usr/local/lib/python3.9/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.9/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) The above exception ((1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' 'foods_nutrient'\n for system_time as of timestamp '2021-0...' at line 1")) was the direct cause of the following exception: File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, … -
Django webserver falis after sending a password reset request email
I have asked this question multiple times now, and it is definitely my fault for not explaining the problem properly, so I have made a short screen-recording that showcases the problem. The URLS: path('reset_password/', auth_views.PasswordResetView.as_view(), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), Settings setup: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '*******@gmail.com' EMAIL_HOST_PASSWORD = *******' Here are the logs, I tried to read them but I got no idea how to fix this error. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 850, in resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [is_nav_sidebar_enabled] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf..get_val at 0x00000285F295D488>>, 'request': <WSGIRequest: GET '/reset_password/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.. at 0x00000285F2B482F0>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x00000285F2A4EE10>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x00000285F2B200F0>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'form': , 'view': <django.contrib.auth.views.PasswordResetView object at 0x00000285F2B201D0>, 'title': 'Password reset', 'LANGUAGE_CODE': 'en-us', 'LANGUAGE_BIDI': False}] "GET /reset_password/ HTTP/1.1" 200 1903 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\conf\locale\en\formats.py first seen with mtime 1603131647.8355522 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\conf\locale\en_init.py first seen with mtime 1603131647.8345575 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\staticfiles\storage.py first seen with mtime 1603131653.6030731 … -
using django project as a standalone file
i need to use my django project in a standalone system where i can't install python, so i try to use pyinstaller on my manage.py file and i added function that opens the browser so when i click on the icon- the project will open automatically in the browser. my manage.py code is: import os import sys import webbrowser import django def open_in_browser(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'feedback.settings') django.setup() from django.core.management import call_command from django.core.wsgi import get_wsgi_application application = get_wsgi_application() webbrowser.open('http://127.0.0.1:8000', new=1) call_command('runserver', '127.0.0.1:8000') def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'feedback.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) open_in_browser() if __name__ == '__main__': main() the code work before pyinstaller but when i try to use pyinstaller the file manage to open the browser but the server stop running so the browser cannot find the page. how can i keep the server running? -
How to run Django APScheduler on a view function
I want to run a Django view every day preferably at a specific time that calls an API and saves the data in a ForeignKey relational model. I can't use the schedule package in python because it requires infinite loop which can't run alongside a web server. Django APScheduler looks like an elegant solution though the problem is view functions take request as an argument which can't be passed to APScheduler which I need to save the data with the user's id thus I'm getting a Name error views.py def sync_data(): api_url = "" access_token = RefreshToken.response headers = { 'Authorization': 'Bearer {}'.format(access_token), 'Content-Type': 'application/json;encoding=utf-8', } user_id = request.user.id response = requests.post(api_url, data=json.dumps(body), headers=headers) r = response.json() s = Model(user=request.user, starttime = startdate , endtime = endate, field = i['value'][0]) s.save() return redirect('app:dash') scheduler.py from .views import sync_data def start(): scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") # run this job every 24 hours scheduler.add_job(sync_data, 'interval', hours=24, name='sync_daily_data', jobstore='default') register_events(scheduler) scheduler.start() print("Scheduler started...", file=sys.stdout) How do I go about this? Appreciate any help I'll get -
Default regex django uses to validate email
recently, I started playing with Django and created a custom form for user registration. In that form to create the field for email I use something like email = forms.EmailField() I observed that address such as a@a.a is considered invalid by the form. Of course this is a nonsense email address. Nonetheless, I wonder how does Django checks for validity. I found some topics on the net discussing how to check for validity of an email address but all of them were providing some custom ways. Couldn't find something talking about the django default validator. In their docs on the email filed they specify Uses EmailValidator to validate that the given value is a valid email address, using a moderately complex regular expression. However that's not very specific so I decided to ask here. -
xmlhttprequest post not posting to view in django
I am having a login page like this which gets data authenticated from google sign-in successfully and after that I need to post the data to the login view function onSignIn(googleUser) { // Useful data for your client-side scripts: var profile = googleUser.getBasicProfile(); console.log("ID: " + profile.getId()); console.log('Full Name: ' + profile.getName()); console.log('Given Name: ' + profile.getGivenName()); console.log('Family Name: ' + profile.getFamilyName()); console.log("Image URL: " + profile.getImageUrl()); console.log("Email: " + profile.getEmail()); var id_token = googleUser.getAuthResponse().id_token; console.log("ID Token: " + id_token); alert("Token*"+id_token); //this gets executed var xhr = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert(this.responseText); } }; request.open('POST', '/login'); //i tried this also 'login' but not working xhr.open('POST', 'http://localhost:8000/login'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { console.log('Signed in as: ' + xhr.responseText); alert("*******Token*"+id_token) xhr.send('idtoken=' + id_token); }; views def login(request): //does not get called if request.method=='POST': print("in login") print(request.body.decode()) ---more code urls.py path('/login', views.login, name="login"), path('',views.login,name="login"), I am getting no response on the view, i am not getting any error on the console also. Can anyone please help here? Thanks. Starting development server at http://localhost:8000/ Quit the server with CONTROL-C. [09/Feb/2021 07:44:13] "GET / HTTP/1.1" 200 3048 [09/Feb/2021 07:45:15] "GET / HTTP/1.1" 200 … -
Distance between two coordinates in swift does not match geodjango query
I am in the process of developing a mobile application in Swift that is connected to a Python/Django backend. I have a group of objects that need to be sorted by location. Each object has a Point representing the coordinate pair. I connect to the backend from the frontend by passing in the source_latitude and source_longitude into the url parameters. I then use geodjangos with geospatial indexing for two different queries: latitude = request.query_params.get('source_latitude', None) longitude = request.query_params.get('source_longitude', None) if latitude is None or longitude is None: return queryset ref_location = Point(float(latitude), float(longitude), srid=4326) return queryset.annotate(distance=Distance('location', ref_location, spheroid=False)).order_by('distance').distinct() In my second query, I need to organize by within a certain range, which includes a radius URL parameter: return Store.objects.filter(location__distance_lte=(ref_location, D(mi=[radius input into from url parameter]))) Since the distance calculated is different for each object on each phone. I calculate the distance to display to the user on the frontend. However, there seems to be a discrepancy with the distance calculated between the frontend and the backend. For some objects that are close in distance, say 1-3 miles, the ordering of the objects is wrong. This is the frontend swift Code let currentLocation = CLLocation(latitude: Double(latitude)!, longitude: Double(longitude)!) let storeLocation = … -
Is there a way to pass in variable to <div> id in django template?
I am new to the Django template language and I am playing around with bootstrap collapses to display my items. Below is my code: {% for item in items %} <div id="accordion"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> {{item.item_name}} </button> </h5> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> {{item.description}} </div> </div> </div> </div> {% endfor %} This is taken from the Bootstrap documentation for collapse, here. In this implementation, all of the items passed in would have the same id, collapseOne. So whenever I click on an item, any item, it would collapse/uncollapse every item on the page. I've tried id="collapse{{item.item_name}}" but that doesn't seem to work. Is there a way to pass in variables in <div> id?