Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am getting the error while connecting django to mongodb database using djongo
I am trying to create dynamic website using Django.For dynamic data i have tried to use mongodb Database.For the connection between mongo db and django ,djongo is used here. After defining the database and tried to the command makemigrations it shows the error. Data definition in Settings file.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'Cake_Bakery', 'CLIENT':{'host':'localhost','port':27017} } } error is given below: (cake) PS D:\Cake Eccomerce\cake\Cake_Bakery> python manage.py makemigrations System check identified some issues: WARNINGS: ?: (urls.W002) Your URL pattern '/products' [name='products'] has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. No changes detected Traceback (most recent call last): File "D:\Cake Eccomerce\cake\Cake_Bakery\manage.py", line 22, in <module> main() File "D:\Cake Eccomerce\cake\Cake_Bakery\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Cake Eccomerce\cake\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Cake Eccomerce\cake\Lib\site-packages\django\core\management_init_.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Cake Eccomerce\cake\Lib\site-packages\django\core\management\base.py", line 415, in run_from_argv connections.close_all() File "D:\Cake Eccomerce\cake\Lib\site-packages\django\utils\connection.py", line 85, in close_all conn.close() File "D:\Cake Eccomerce\cake\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "D:\Cake Eccomerce\cake\Lib\site-packages\django\db\backends\base\base.py", line 358, in close self._close() File "D:\Cake Eccomerce\cake\Lib\site-packages\djongo\base.py", line 208, in _close if self.connection: File "D:\Cake … -
getting error TypeError at /login/ ChatroomMiddleware.__call__() missing 2 required positional arguments: 'receive' and 'send'
i am trying to create a middleware for my chatroom/consumer so that i can access current logged-in user object in my consumer.py, but getting a error "getting error TypeError at /login/ ChatroomMiddleware._call_() missing 2 required positional arguments: 'receive' and 'send'" chatroom/consumer.py ( chatroom is app of my project) import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from chatroom.views import get_user_exist class GlobalChatConsumer(AsyncWebsocketConsumer): roomID = "global_room" sender = None message = "" async def connect(self): self.sender = self.scope["user"] print("USER ----> $", self.sender) await self.channel_layer.group_add(self.roomID, self.channel_name) await self.accept() messages = await self.retrieve_room_messages() async for message in messages: sender_username = await database_sync_to_async(lambda: message.sender.username)() await self.send( text_data=json.dumps( { "type": "chat_message", "message": message.content, "sender": sender_username, } ) ) async def disconnect(self, close_code): await self.channel_layer.group_discard(self.roomID, self.channel_name) async def receive(self, text_data): text_data_json = json.loads(text_data) message_type = text_data_json.get("type") self.message = text_data_json.get("message") print("Message type", message_type) print("Message -> ", self.message) if message_type == "join_room": self.roomID = text_data_json.get("roomID") await self.channel_layer.group_add(self.roomID, self.channel_name) await self.send( text_data=json.dumps( {"type": "info", "message": f"You have joined room {self.roomID}"} ) ) elif message_type == "chat_message": await self.save_chat_db() await self.channel_layer.group_send( self.roomID, { "type": "chat_message", "message": self.message, "sender": self.scope.get("user").username, }, ) async def chat_message(self, event): message = event["message"] sender = event["sender"] await self.send( text_data=json.dumps( { "type": "chat_message", "message": … -
Django API attribute not found
I am building an API using django and the django rest framework that uses models from tensorflow and scikit-learn. I have ran into an error where my CountVectorizer that I fitted and used in another python script and used pickle to export and import into my django project, raises an attribute error when I try to make a call to the API View. This is the error: Traceback (most recent call last): File "/home/dude/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/dude/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/dude/.local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/home/dude/.local/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/dude/.local/lib/python3.10/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File "/home/dude/Desktop/Projects/Finance Webapp/Financial_Chatbot_API/chatbot/views.py", line 36, in chatbotRequestHandler chatbotObj = ChatBot() File "/home/dude/Desktop/Projects/Finance Webapp/Financial_Chatbot_API/chatbot/functions.py", line 100, in __init__ AttributeError: Can't get attribute 'custom_preprocessor' on <module '__main__' from '/home/dude/Desktop/Projects/Finance Webapp/Financial_Chatbot_API/manage.py'> [25/Nov/2023 00:23:44] "POST / HTTP/1.1" 500 96891 This is my api view: @api_view(['POST']) data = request.data chatbotPrompt … -
How can I patch a celery task
I'd like to know how I can write unit tests to test a celery task correctly. Unfortunately, the internet gives testing examples of very simple celery tasks. My case looks as follows: I have a custom admin command which is a celery task that does 3 things: Makes a xlsx file from DB data, Uploads the xlsx file to s3, Send a link to the file to the request user (admin). I'd like to test 2 assertions: to test the file itself (that the xlsx file has correct DB data). But I don't understand how I can read the file which is created in the celery task to compare what the file has against the data in the DB. to test that the link is sent to the admin correctly. (I can do it in my second attempt) The code looks like this: Admin site: @admin.register(MyModal) class MyModelAdmin(admin.ModelAdmin): def export_xlsx(self, request, queryset): my_celery_task.delay(ids, queryset, request.user) actions = [export_xlsx] Celery task: @app.task(ignore_result=True) def my_celery_task(ids, queryset, user): # 1) makes a xlsx wb = openpyxl.Workbook() ws = wb.active # blablah wb.save(filename='/tmp/temp.xlsx') # 2) uploads to s3 s3 = boto3.resource('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, endpoint_url=settings.AWS_S3_ENDPOINT_URL) s3.Bucket(settings.AWS_STORAGE_BUCKET_NAME).upload_file('/tmp/temp.xlsx', 'file.xlsx') # 3) sends a link to the admin … -
How to customize the text for django humanize - naturaltime?
I'm using django humanize with the "naturaltime" template filter in my templates Right now it returns future dates as: "3 days from now" I'd like to customize it into something like "in 3 d" (so also changing the order of the words in the output) How would I go about doing that? -
Getting "OutstandingToken.user" must be a "User" instance
I am creating a register method using djangorestframework-simplejwt. I created a custom user in auth using AbstractBaseUser. This is my views.py: class GoogleSocialAuthView(GenericAPIView): serializer_class = GoogleSocialAuthSerializer def post(self, request): """ POST with "auth_token" Send an idtoken as from google to get user information """ serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) data = ((serializer.validated_data)['auth_token']) return Response(data, status=status.HTTP_200_OK) serializers.py class GoogleSocialAuthSerializer(serializers.Serializer): auth_token = serializers.CharField() def validate_auth_token(self, auth_token): user_data = google.Google.validate(auth_token) print("login status", user_data) #try: user_data['sub'] #except: #raise serializers.ValidationError( #'The token is invalid or expired. Please login again.' #) if user_data['aud'] != os.environ.get('GOOGLE_CLIENT_ID'): raise AuthenticationFailed('oops, who are you?') user_id = user_data['sub'] email = user_data['email'] name = user_data['name'] provider = 'google' return register_social_user( provider=provider, user_id=user_id, email=email, name=name) My custom user model: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) groups = models.ManyToManyField( Group, verbose_name='groups', blank=True, help_text= 'The groups this user belongs to. A user will get all permissions ' 'granted to each of their groups.' , related_name="my_auth_user_set", related_query_name="user", ) user_permissions = models.ManyToManyField( Permission, verbose_name='user permissions', blank=True, help_text='Specific permissions for this user.', related_name="my_auth_user_set", related_query_name="user", ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = … -
PyTorch AssertionError: "Torch not compiled with CUDA enabled" in Django application
I'm encountering an issue in my Django application where I'm using PyTorch to initialize a model, and I'm getting an AssertionError with the message "Torch not compiled with CUDA enabled." This happens when trying to access GPU functionality. Details: Django Version: 3.0.5 Python Version: 3.6.2 PyTorch Version: CUDA Version: [12.3] Operating System: [win 11] Code Snippet: python Copy code # Relevant code snippet where the error occurs from torch import Model # ... def predict_page(request): model = Model(2).cuda() # ... Troubleshooting Steps Taken: Checked PyTorch installation. Verified CUDA installation. Updated PyTorch and CUDA to the latest versions. Conditionally initialized the model based on GPU availability. Checked GPU availability using torch.cuda.is_available(). Additional Notes: I've ensured that my system has a compatible GPU. I've restarted the Django development server after making changes. Question: What could be causing this error? Are there any specific configurations I need to check? Is there a compatibility issue between PyTorch, CUDA, and Django? Any help or guidance on resolving this issue would be greatly appreciated! AssertionError at /predict/ Torch not compiled with CUDA enabled Request Method: GET Request URL: http://127.0.0.1:8000/predict/ Django Version: 3.0.5 Exception Type: AssertionError Exception Value: Torch not compiled with CUDA enabled Exception Location: D:\ai\Deepfake_detection_using_deep_learning\Django … -
Django dynamic formsets hidden field error
I wanted to add button for dynamcially adding an instance of formset in dajngo. I use django-dynamic-formset for this. The problem is that if I add formset by the button and try to submit the below error appears: (Hidden field TOTAL_FORMS) This field is required. (Hidden field INITIAL_FORMS) This field is required. I read that it is caused by not including "form.managment_form" in a template, but I've included it: Here is a template code: {% extends "mainapp/base.html" %} {% block content %} {% load static %} {% load widget_tweaks %} <!-- Include necessary scripts and CSS for dynamic formset --> <script type="text/javascript" src="{% static 'jquery-3.7.1.min.js' %}"></script> <script type="text/javascript" src="{% static 'jquery.formset.js' %}"></script> <!-- <link rel="stylesheet" type="text/css" href="{% static 'formset/jquery.formset.css' %}"> --> <div id="input-div1"></div> <div class="input-div2"> <form method="post"> {% csrf_token %} {{ simulation_form.initial_amount.label_tag }} {{ simulation_form.initial_amount|add_class:"form-control"}} {{ simulation_form.number_of_simulations.label_tag }} {{ simulation_form.number_of_simulations|add_class:"form-control" }} {{ simulation_form.number_of_trades.label_tag }} {{ simulation_form.number_of_trades|add_class:"form-control" }} <br> <div class="strategy-formset"> {{ strategy_formset.management_form }} {% for form in strategy_formset %} {{ form.as_p }} {% endfor %} </div> <button type="submit" name="save" class="btn btn-primary">Submit</button> </form> </div> <script type="text/javascript"> $(function () { $('.strategy-formset').formset({ prefix: '{{ strategy_formset.prefix }}' }); }); </script> {% endblock %} Do you know what else can cause this error? Thanks in … -
Why I'm receiving the 'Connection time out' when I try to run the 'python manage.py migrate' code on putty?
Ok, I'm trying to deploy a Django project using EC2 instance I've already created an RDS/Postgree database and test it through my IDE before deploy it and it's working correctly But when I try to run the 'python manage.py migrate' code on putty I'm receiving this error angtradingdb.xxxxxxx.rds.amazonaws.com" (xxxxxxx), port 5432 failed: Connection timed out I've set 2 inbound rules on my RDS instance: First I put PostgreSQL as 'Type', 'TCP' as Protocol, 5432 as 'Port Range' and my IP as 'Source' Second inbound rule, it's the same thing but the VPC security group of my EC2 application as 'Source' I've done that before and those 2 rules where enough for the deployment to work Any idea of what can be causing this error? -
Django stops serving static files after a while
I recently built my first website with Django, loaded up all my static files, both js and scss scripts, and some pics. All works well, file uploads work, etc. Works fine after deploying to Azure as well. The problems started some time ago when my css stopped generating any changes in the pages layout (its not the scss mapping cause it works locally, and I see the changes in the css). I checked and when it occurs js files dont work also. It only loads up the changes up to my last commit and nothing after it, even though the server loads up the files from the disk with no errors. I thought it has something do to with version conflicts in the git but I resolved all of them, and it still didn't fix it. Tried restarting chrome, deleting cache files, hard reset. Collectstatic doesn't do anything at all. It sometimes works, and then just stops. Restarting the server, even the computer (I am desperate) doesn't work either. I checked the settings.py and the static files are all routed correctly: STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'mainsite/static' I am in debug mode when I develop the app locally. … -
Django with mypy: How to resolve incompatible types error due to redefined field for custom `User` model class that extends "AbstractUser"?
I have an existing Django project which uses a custom User model class that extends AbstractUser. For various important reasons, we need to redefine the email field as follows: class User(AbstractUser): ... email = models.EmailField(db_index=True, blank=True, null=True, unique=True) ... Typing checks via mypy have been recently added. However, when I perform the mypy check, I get the following error: error: Incompatible types in assignment (expression has type "EmailField[str | int | Combinable | None, str | None]", base class "AbstractUser" defined the type as "EmailField[str | int | Combinable, str]") [assignment] How can I make it so that mypy allows this type reassignment? I don't wish to just use # type: ignore because I wish to use its type protections. For context, if I do use # type: ignore, then I get dozens of instances of the following mypy error instead from all over my codebase: error: Cannot determine type of "email" [has-type] Here are details of my setup: python version: 3.10.5 django version: 3.2.19 mypy version: 1.6.1 django-stubs[compatible-mypy] version: 4.2.6 django-stubs-ext version: 4.2.5 typing-extensions version: 4.8.0 -
Argument of type "Literal['result']" cannot be assigned to parameter "__key" of type "SupportsIndex | slice" in function "__getitem__"
CODE def youtube(request): if request.method == "POST": form = DashboardFom(request.POST) text = request.POST['test'] video = VideosSearch(text,limit=10) result_list = [] for i in video.result()['result']: result_dict = { 'input':text, 'title':i['title'], 'duration':i['duration'], 'thumbnail':i['thumbnails'][0]['url'], 'channel':i['chanel']['name'], 'link':i['link'], 'views':i['viewCount']['short'], 'published':i['publishedTime'] } desc = '' if i['descriptionSnippet']: for j in i['descriptionSnippet']: desc += j['text'] result_dict['description'] = desc result_list.append(result_dict) context = { 'form':form, 'results':result_list } return render(request,"dashboard/youtube.html",context) else: form = DashboardFom() context = {'form':form} return render(request,"dashboard/youtube.html",context) From the above block of code the following code gives error for i in video.result()['result'] The error message is -- Argument of type "Literal['result']" cannot be assigned to parameter "__key" of type "SupportsIndex | slice" in function "__getitem__" Type "Literal['result']" cannot be assigned to type "SupportsIndex | slice" "Literal['result']" is incompatible with protocol "SupportsIndex" "__index__" is not present "Literal['result']" is incompatible with "slice"PylancereportGeneralTypeIssues) Also the following dictionary gives error--- result_dict = { 'input':text, 'title':i['title'], 'duration':i['duration'], 'thumbnail':i['thumbnails'][0]['url'], 'channel':i['chanel']['name'], 'link':i['link'], 'views':i['viewCount']['short'], 'published':i['publishedTime'] } The error message is --- Argument of type "Literal['title']" cannot be assigned to parameter "__key" of type "SupportsIndex | slice" in function "__getitem__" Type "Literal['title']" cannot be assigned to type "SupportsIndex | slice" "Literal['title']" is incompatible with protocol "SupportsIndex" "__index__" is not present "Literal['title']" is incompatible with "slice"PylancereportGeneralTypeIssues) -
pymongo count_doucment() not working with datetime
Hi i am trying to query data from mongodb using python = 3.8, django=4.2.2, arrow==1.2.3 pymongo = 3.13.0 this is my filter object filter['created_at']={ '$gte': arrow.now(settings.LOCAL_TIME_ZONE).shift(hours=-24).span('day')[0].to(settings.TIME_ZONE).datetime, '$lt': arrow.now(settings.LOCAL_TIME_ZONE).span('day')[1].to(settings.TIME_ZONE).datetime, } when i print filter['created_at'] i get output as 'created_at': {'$gte': datetime.datetime(2023, 11, 22, 18, 30, tzinfo=tzutc()), '$lt': datetime.datetime(2023, 11, 24, 18, 29, 59, 999999, tzinfo=tzutc())} and this is my count function def count(self, filters={}): q = self.collection.count_documents(filters) return q when i pass empty {} in filter i get count of documents -
Submit file on GitHub
I once uploaded a Django file to GitHub, and after making some changes, I want to upload it again, but it gives me this error. Can you tell me what I should do? C:\Users\Desktop\project1>git add . C:\Users\Desktop\project1>git commit -m "project1_new" C:\Users\Desktop\project1>git push origin --all Enumerating objects: 3, done. Counting objects: 100% (3/3), done. Writing objects: 100% (2/2), 233 bytes | 233.00 KiB/s, done. Total 2 (delta 0), reused 0 (delta 0), pack-reused 0 To https://github.com/me50/ZZZZZZZZ.git 2c0ea43..cfae680 check50/projects/2020/x/wiki -> check50/projects/2020/x/wiki ! [rejected] web50/projects/2020/x/search -> web50/projects/2020/x/search (fetch first) ! [rejected] web50/projects/2020/x/wiki -> web50/projects/2020/x/wiki (fetch first) error: failed to push some refs to 'https://github.com/me50/ZZZZZZZZ.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. -
sudo: python: command not found for django migration to mysql database
I want to connect my current project to mysql databse which I created before with root user I want to connect my current project to mysql databse which I created before with root user but every time I want to use it, I get the error sudo: python: command not found how could I fix this? (I don't want to run that with another user, because some reasons I want use root user) -
Is it possible to combine a regex url pattern with url converter
I have two different paths in django-project urls re_path(internal_site_url, internal_site), #for internal sites #internal_site_url is re_pattern path('<path:site_url>', external_site) #for external sites but re_path in first path would not include path converter path:site_url for further usage in a view, in comparison with the second one. So how could I achive combining re-pattern match with path conversion? -
Cookiecutter Django project postgres migrating to new host
I have a cookiecutter django template project working fine with a local postgres database. (https://cookiecutter-django.readthedocs.io/en/latest/) I've copied the git repository and recreated the docker images on a new host to run in production, but I would like to export/copy my data as well. What's the recommended way to move the data over from the postgres docker instance ? Thanks -
Django url issue while calling in Postman
I am creating CRUD operation in Django, REST API and Mongo DB. I have done the basic CRUD code. When I try to call the api in postman, I am not getting any responses. In the pycharm, I am seeing the below issue, "POST /emp/registration%0A HTTP/1.1" 404 2297 Not Found: /emp/registration Here is my project structure. DjangoAPI.urls.py from django.urls import path from django.urls import re_path from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('emp/', include('EmployeeApp.urls')), ] DjangoAPI.EmployeeApp.urls.py from EmployeeApp import views from django.conf.urls.static import static from django.conf import settings from django.urls import path urlpatterns = [ path('registration', views.registrationApi), ] DjangoAPI.settings.py Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os BASE_DIR=Path(__file__).resolve(strict=True).parent.parent MEDIA_URL='/Photos/' MEDIA_ROOT=os.path.join(BASE_DIR,"Photos") # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-@oxx-o(4f=mxha%-tlv97)x9m7x_fw=(@*k=*29q%r7c8*)%-&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', … -
REST api url not found issue
I am doing CRUD operation in Django + REST API + Mongo DB. I have done the basic CRUD code. When I try to call the api in postman, I am not getting any responses. In the pycharm, I am seeing the below issue, "POST /emp/registration%0A HTTP/1.1" 404 2297 Not Found: /emp/registration Here is my project structure. DjangoAPI.urls.py from django.urls import path from django.urls import re_path from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('emp/', include('EmployeeApp.urls')), ] DjangoAPI.EmployeeApp.urls.py from EmployeeApp import views from django.conf.urls.static import static from django.conf import settings from django.urls import path urlpatterns = [ path('registration', views.registrationApi), ] DjangoAPI.settings.py Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os BASE_DIR=Path(__file__).resolve(strict=True).parent.parent MEDIA_URL='/Photos/' MEDIA_ROOT=os.path.join(BASE_DIR,"Photos") # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-@oxx-o(4f=mxha%-tlv97)x9m7x_fw=(@*k=*29q%r7c8*)%-&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ … -
How to access a Django variable in an external JavaScript?
I am making a Django website. In it I am trying to access a variable in view.py file in an external static JS file linked to my template. I tried using the syntax var is_empty = "{{is_empty}}", but it didn't work in a if statement where if(Number(is_empty) == 1), and also I tried creating a div in my body(with id = "temp") and adding an attribute data-dj = {{is_empty}} and then using var is_empty = document.getElementById("temp").getAttribute("data-dj");, but it was showing an error that cannot call getAttribute on null. Please help! -
how to overwrite value filled with POST
I'm trying to pass list of ids into hidden field: the POST result is: POST in add_document:<QueryDict: {'csrfmiddlewaretoken': ['xxx', 'xxx'], 'person_ids': ['15129', '15161', '15177', '15217'], 'submit': ['Submit']}> views.py: (...) add_document_form = DocumentForm(request.POST or None, context = context, initial={'person_ids': '1'}) context['add_document_form'] = add_document_form print(add_document_form.fields['person_ids'].initial) html_template = loader.get_template('backend/' + context['load_template']) return HttpResponse(html_template.render(context, request)) (...) forms.py: class DocumentForm(forms.ModelForm): # person_ids = forms.MultipleChoiceField(widget = forms.HiddenInput()) person_ids = forms.CharField(widget = forms.HiddenInput()) def __init__(self, *args, **kwargs): context = kwargs.pop('context', None) super(DocumentForm, self).__init__(*args, **kwargs) print(self.fields['person_ids'].initial) self.fields['person_ids'].initial = '2' print(self.fields['person_ids'].initial) But whatever I do - finally I got <input type="hidden" name="person_ids" value="15217" id="id_person_ids"> Django totally ignores my initial settings... (while print always printing the correct values... My best solution would be: <input type="hidden" name="person_ids" value="['15129', '15161', '15177', '15217']" id="id_person_ids"> Changing widget to TextField changes nothing. The value of person_ids is still '15217' -
javascript request origin determination
I have a general Javascript question The setup Webserver ( number 1 ) with a website that uses html and javascript A second ( number 2 ) webserver with Apache and Django Webserver 1 with html / javascript page < ------- javascript applications requests data from Webserver 2 ---------- > Webserver 2 The website from point 1 runs a javascript application that sends data to the web server number 2. How can I make sure that web server number 2 only accepts http requests from the javascript application of web server number 1 ? For example I had thought of a csrf token. Is this already a good approach, are there any other possibilities I have? Thanks in advance. -
How to process secondary sourse links via django views?
Let's say I have the following home.html template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>home</title> <link rel="icon" type="image/png" href="{% static 'images/favicon-32x32.png' %}" > <link rel="stylesheet" href"/stylesheet_url"> </head> <body> </body> </html> and urls look like that: urls = [ path('home/', home) ] and home view is: def home(): return render(request, 'home.html') how should the any-referral view and any-referral url look like, so I could process request that uses any referral from inside of any resourse? The Idea for url is that if I firstly specify all the concreate urls, then the last url in urls could be matching any url left. But the main problem seems that the veiw does not trigger on any url pattern (currently my everymatching url looks like path('<path:referral>', any_refferal). Also I suspect that there stands a different mechanism behind using referrals from inside of page, compared to one that that processes the page -
How to do visudo edit in sudoers.d automatically in Python?
I have a complex django-application and want to add the option for the user to shutdown the server (a Raspberry Pi) from the django-webmenu. Because the django-process on the Raspi does not have sudo privileges, I decided to give the shutdown privilege to my user via an additional configfile in sudoers.d. So I added two lines to execute to my installation instructions: To create the new file with visudo: sudo visudo -f /etc/sudoers.d/shutdown_privilege And than add one line to that file: cam_ai ALL=(root) NOPASSWD: /sbin/shutdown This works nicely, but now I would like to move this complication into my (Python-)installation script. This does not work. What am I doing wrong? I tried several things: subprocess.call(['sudo', 'touch', '/etc/sudoers.d/shutdown_privilege']) subprocess.call(['sudo', 'sed', '-i', '$acam_ai ALL=(root) NOPASSWD: /sbin/shutdown' , '/etc/sudoers.d/shutdown_privilege']) cmd = 'echo "cam_ai ALL=(root) NOPASSWD: /sbin/shutdown" | sudo tee -a /etc/sudoers.d/shutdown_privilege' subprocess.call(cmd, executable='/bin/bash') The only thing that worked is the touch command in the first line. The rest stops the program execution or does just nothing... -
django-smart-selects query filter
I am using django-smart-selects to create chained dropdown forms, problem is I cannot filter querysets made by this package since it creates its own formsets. normally i would override init such : def __init__(self,*args, **kwargs): super(BookingForm, self).__init__(*args, **kwargs) self.fields['booked_time'].queryset = AvailableHours.objects.filter(status=True) in my forms.py but now this package is overriding entire form in admin and in user views. I need to filter the query so that only objects with Status=True are fetched my forms.py : class BookingForm(forms.ModelForm): class Meta: model = Bookings exclude = ('user','booking_code','confirmed',) def __init__(self,*args, **kwargs): super(BookingForm, self).__init__(*args, **kwargs) self.fields['booked_time'].queryset = AvailableHours.objects.filter(status=True) my models.py: AVAILABLE_DATE_CHOICES = ( (True, 'فعال'), (False, 'غیرفعال'), ) class AvailableDates(models.Model): free_date = jmodels.jDateField(null=True, verbose_name="تاریخ فعال",) status = models.BooleanField(choices=AVAILABLE_DATE_CHOICES,null=True,default=True, verbose_name="وضعیت",) class Meta: verbose_name_plural = "روزهای فعال" verbose_name = "روز فعال" ordering = ['-free_date'] def __str__(self): return f'{str(self.free_date)}' class AvailableHours(models.Model): free_date = models.ForeignKey(AvailableDates,verbose_name="تاریخ فعال", null=True, blank=True,on_delete=models.DO_NOTHING,related_name='freedate') free_hours_from = models.IntegerField(null=True, blank=True, verbose_name="از ساعت",) free_hours_to = models.IntegerField(null=True, blank=True, verbose_name="الی ساعت",) status = models.BooleanField(null=True,default=True, verbose_name="آزاد است؟",) class Meta: verbose_name_plural = "سانس ها" verbose_name = "سانس" def __str__(self): return f'{str(self.free_date)} - {self.free_hours_from} الی {self.free_hours_to}' class Bookings(models.Model): user = models.ForeignKey(User,on_delete=models.DO_NOTHING, null=True, verbose_name="کاربر",) booker_name = models.CharField(max_length=100, null=True, verbose_name="نام",) booker_service = models.ForeignKey(BarberServices, null=True, on_delete=models.DO_NOTHING, verbose_name='خدمات') booked_date = models.ForeignKey(AvailableDates, null=True, on_delete=models.DO_NOTHING,related_name='booked_date', verbose_name="روز",) booked_time = …