Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Easiest way to Normalizing data in models Parent Child tables Django Models
Trying to find the easiest way to make an meta abstract Child Model and meta abstract Parent Model with the same column "data" unique, The Child Models that I create will inherit the meta abstract Child Model will have column names in reference to the Parent Model Names. Something that can get_or_create into the Parent Models, while saving into the Child Model from django.db import models from django.apps import apps class ParentCharField(models.CharField): description = "A unique not null charfield for normalized parent tables" def __init__(self, *args, **kwargs): kwargs['unique'] = True kwargs['null'] = False super().__init__(*args, **kwargs) class ParentModel(models.Model): data = ParentCharField(max_length=10) class Meta: abstract = True class ChildModel(models.Model): def getModels(self): return apps.get_models() def get_model_name(self, value): model_name = value.capitalize() models = apps.get_models() for i in models: p = i.__name__.split('.')[-1] if model_name in p: return i def get_parent_object(self, name, value): object_cls = self.get_model_name(name) if object_cls: objected, created = object_cls.objects.get_or_create(data=value) return object_cls.objects.get(id = objected.id) def save(self, *args, **kwargs): fields = [i.name for i in self._meta.fields][1:] newargs = [] newkwargs = {} if args: p=0 for i in args: newargs.append(self.get_parent_object(fields[p],i)) p += 1 if kwargs: for i, v in kwargs.items(): newkwargs[i] = self.get_parent_object(i, v) models.Model.save(self, *newargs, **newkwargs) class Meta: abstract = True class Cik(ParentModel): pass … -
OSError: [Errno 24] Too many open files in Django app served by Gunicorn
I have an exception in my Django application served by Gunicorn / Nginx with no detailed information available. The error is captured in Sentry logging system on a regular basis. Any hints in which direction I should dig? exception OSError: [Errno 24] Too many open files socket.py in accept at line 292 self <socket.socket fd=9, family=AddressFamily.AF_UNIX, type=SocketKind.SOCK_STREAM, proto=0, laddr=/opt/trading-backend/trading-backend.sock> gunicorn/workers/sync.py in accept at line 28 gunicorn/workers/sync.py in run_for_one at line 69 gunicorn/workers/sync.py in run at line 125 gunicorn/workers/base.py in init_process at line 142 gunicorn/arbiter.py in spawn_worker at line 589 -
how to run loader on successful form submission only?
I want that the loader should start ONLY and ONLY when the form has been successfully submitted (instead of just the onclick submit button event that the code does currently). How can I do so? <div id="loader" class= "lds-dual-ring hidden overlay" > <div class="lds-dual-ring hidden overlay"> </div> <div class="loadcontent"><div><strong>Working on your request...it may take up to 2 minutes.</strong></div></div> </div> Code below is the part where loader kicks upon submit button event. $('#submitBtn').click(function () { $('#loader').removeClass('hidden') // $('#loader').html('Loading').addClass('loadcontent') // $("#loading").html("Loading"); }) </script> Code below is one of the form fields that takes a value from user: <div class="form-group"> <div class="form-control"style="padding: 0;"> {% ifequal field.name 'Port' %} {% render_field field class="rowforinput marginforfields form-control" style="height: 23px; margin-left: 0; margin-right: 0" title=" For eg. 1/1/48 or 2/1/16" pattern="^[12]/1/(?:[1-3]\d|4[0-8]|[1-9])$" required=true %} {% endifequal %} </div> </div> -
how to extract data from the database and pass it to the function in Django
I`m beginner Django user, please help me. I have multiple records in a sqlite3 data table. Please tell me how to read this data from the database in Django and write it to the views.py function. This is my models.py class Value(models.Model): capacity = models.FloatField('Емкость конденсатора') amplitude = models.FloatField('Амплитуда') frequency = models.FloatField('Частота') This is my views.py def voltage(array, a, c, w, tim): t = 0 for i in range(100): array.append(c * a * math.sin(w * t - math.pi / 2)) tim.append(t) t = t + 0.1 someArray = [] tim = [] voltage(someArray, a, c, tim) in c I want to write capacity, in a - amplitude, in w - frequency. I hope I can get data from the database into the views.py function -
is it possible to avoid n+1 django query here? If so, how?
I have these models class Thing1(MyModel): thing2 = models.OneToOneField( Thing2, on_delete=models.PROTECT, related_name="super_pack" ) some_id = models.IntegerField() class Thing2(MyModel): name = models.CharField(max_length=50, primary_key=True) class Thing3(MyModel): name = models.CharField(max_length=255) thing2 = models.ForeignKey( Thing2, related_name="thing3s", ) class Thing4(MyModel): root_thing3 = models.OneToOneField( Thing3, on_delete=models.PROTECT, related_name="my_related_name" ) member_item_thing3s = models.ManyToManyField( Thing3, through="unimportant", related_name="important_related_name", ) is_default = models.BooleanField(default=False) I'm working with a Django serializer. Already defined I have a queryset with prefetching. As it stands, the following is performant: all_thing1s: QuerySet[Thing1] for thing1 in all_thing1s: first_thing3 = Thing1.thing2.thing3s.all()[0] (from now on assume we are in the loop body) which is not ideal, if there is always 1 thing3 the schema shouldn't allow for many, but I can't change the schema at this time.) At this point I believe the ability to pre-fetch further has been broken because we have returned a Thing3 (first_thing3) and no longer have a query set to work with At the start of this I thought Django magically used previous prefetches, I didn't realize that the filters etc. that you wanted to make use of the prefetches had to be chained to the prefetches. But now I want to do: thing4 = first_thing3.important_related_name.all()[0] return thing4.root_thing3 (note: first_thing3 and root_thing3 share the same … -
Django select from many-to-many
The basic model. class Game(models.Model): date = models.DateField() ... class Player(models.Model): user = models.OneToOneField(User, default=None, on_delete=models.CASCADE) games = models.ManyToManyField(Game, through='PlayerGame') ... class PlayerGame(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE) score = models.IntegerField() ... Each game will have two players with their respective scores. When one player/user is logged in, I'd like to display all their games against other players. e.g. Player 1 logged in... Date Opponent Your Score Opponent Score 2022-01-01 Player 2 31 27 2021-06-02 Player 4 31 26 2021-06-02 Player 2 5 31 2021-05-27 Player 6 20 31 If Player 2 was logged in, they may see Date Opponent Your Score Opponent Score 2022-01-01 Player 1 27 31 2021-06-02 Player 1 31 5 Any ideas on how to write a query for this? -
Django and adding a static image
Good evening, I've just completed this tutorial: https://docs.djangoproject.com/en/4.1/intro/tutorial01/ and I need to add a new directory to display a dataset (unrelated to the polls app) I've set up my new directory as I did the first steps in the tutorial. My steps: ...\> py manage.py startapp newendpoint newendpoint/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py urls.py views.py path('newendpoint/', include('newendpoint.urls')) **Once this is setup I've tried these tutorials: ** https://youtu.be/u1FR1nZ6Ng4 I've tried this tutorial and had no luck https://adiramadhan17.medium.com/django-load-image-from-static-directory-27f002b1bdf1 I've also tried this one My server goes down or nothing displays. I could really use some help getting this figured out, before I tried the static image I was trying to add a csv via SQLite3 with no luck either. -
How do I overwrite Bootstrap SCSS variables for my django website using PyCharm?
I'm using PyCharm to manage my django files and for the front end I'm using Bootstrap. I'm currently using the CDN method to point to the bootstrap files in my base.html file. I've recently come to a point where I want to customize some of the SCSS variables that bootstrap provides, but I'm puzzled and can't find a guide anywhere to how to do this with my configuration. I used npm to install the bootstrap files to my outer project folder. I've tried installing django-sass-compiler using pip, and then adding the required setting to my settings.py, but when I ran the command "python manage.py sass-compiler" (as per the PyPi docs), I got "ModuleNotFoundError: No module named 'django_sass_compiler'" I'm assuming that if I were to get that working then it would compile my custom SCSS file into a CSS file that would overwrite my current 'main.css' (is that right?), however I can't even figure out that part. If someone could please point me in the right direction then that would be great, there really isn't a lot of help out there for sass, pycharm, django & bootstrap together. -
[ODBC Driver 17 for SQL Server][SQL Server]Cannot open server <server name> requested by the login. The login failed. (40532) (SQLDriverConnect)')
Using mssql-django package to connect to SQL server. It is working fine in Local Azure Virtual Machine. But when I deploy Django using Azure Function App, It is giving me the above error. Is anyone faced the same issue. I am not sure why it is not working when i deploy app in Azure function app. Is there any function app configuration that I need to change? -
Elastic beanstalk failed deployment
After deploying with Beanstalk, I have this error : Instance deployment failed. For details, see 'eb-engine.log'. It's just after this one : Added instance [i-0ca6b54779ee5d6ce] to your environment. Do you have any ideas?Error message I was trying to deploy a django web-app using elastic beanstalk. I expected a successful deployment but faced some error messages that i can not solve. -
In Django, how to make a join query with matching conditions in addition to the foreign key?
We have a hand-written SQL query for proof of concept and hope to implement the function with the Django framework. Specifically, Django's QuerySet usually implements a join query by matching the foreign key with the primary key of the referred table. However, in the sample SQL below, we need additional matching conditions besides the foreign key, like the eav_phone.attribute_id = 122 in the example snippet below. ... left outer join eav_value as eav_postalcode on t.id = eav_postalcode.entity_id and eav_phone.attribute_id = 122 ... Question: We wonder if there is a way to do it with the Django framework or libraries. Technical Details: The scenario is a report that consists of transactions with customized columns by Django-EAV. This library implements the eav_value table consists of columns of different data types, e.g. value_text, value_date, value_float, etc. So, the application defines a product with attributes in specific data types, and we referred it as metadata in this question, e.g.: attribute_id slug datatype 122 postalcode text 123 phone text ... ... e.g. date, float, etc. ... We are using a forked reposition of Django-EAV, not Django-EAV2, but the new version follows the same database schema design as far as we know. So, one transaction is … -
I'm getting an error while trying to run docker-compose to configure a django project and mysql database, on Ubuntu 22.04
I am new to docker and still learnig it, so I was coding along this youtube tutorial but when I try to run the docker compose file I'm getting these errors on my machine which I can't seem to understand. Here is the docker-compose.yml contents: version: "3.8" services: app: build: . volumes: - .:/django ports: - 8000:8000 image: app:django container_name: django_container command: python manage.py runserver 0.0.0.0:8000 depends_on: - db db: image: mysql:5.7 environment: MYSQL_DATABASE: 'django-app-db' MYSQL_ALLOW_EMPTY_PASSWORD: 'true' volumes: - ./data/mysql/db:/var/lib/mysql Dockerfile: FROM python:3.8-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt Requirements.txt file: asgiref==3.5.2 Django==4.1.3 pytz==2022.6 sqlparse==0.4.3 psycopg2-binary>=2.9 mysqlclient>=2.1 Now when I run docker-compose build or the next commnad docker-compose run --rm app django-admin startproject core ., thats when I'm getting these errors: Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [16 lines of output] mysql_config --version /bin/sh: 1: mysql_config: not found mariadb_config --version /bin/sh: 1: mariadb_config: not found mysql_config --libs /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/tmp/pip-install-lbql0nv5/mysqlclient_b1015c8235e44329ba5248fc9f64b86b/setup.py", line 15, in … -
'NoneType' object is not subscriptable in Django
I'm writing tests for views.py and check that the context of the main page, that it is formed correctly, and when checking, such an error crashes def test_index_page_show_correct_context(self): """Шаблон index сформирован с правильным контекстом.""" response = self.guest_client.get(reverse('posts:index')) excepted_object = Post.objects.all()[:TEST_NUM] > self.assertEqual(response.context['page_obj'], excepted_object) E TypeError: 'NoneType' object is not subscriptable Code: class PostViewsTest(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = User.objects.create_user(username='auth') cls.group = Group.objects.create( title='Тестовая группа', slug='test-slug', description='Тестовое описание', ) cls.post = Post.objects.create( author=cls.user, text='Тестовый пост', group=cls.group ) cls.comment = Comment.objects.create( text='Тестовый комментарий', author=cls.user ) def setUp(self): self.guest_client = Client() self.authorized_client = Client() self.authorized_client.force_login(PostViewsTest.post.author) def test_index_page_show_correct_context(self): """Шаблон index сформирован с правильным контекстом.""" response = self.guest_client.get(reverse('posts:index')) excepted_object = list(Post.objects.all()[:TEST_NUM]) self.assertEqual(list(response.context['page_obj']), excepted_object) -
How to hide/show a register with djangoadmin?
I have a model with customers in my front I have a combobox with the list of my customers. how I can in djangoadmin hide or show this customers? I think it could be a checkbox like "this customer is active/inactive" but how can I solve this with djangoAdmin? I think it could be a checkbox like "this customer is active/inactive" but how can I solve this with djangoAdmin? -
How to Create a Pandas DataFrame from multiple list of dictionaries
I want to create a pandas dataframe using the two list of dictionaries below: "country_codes": [ { "id": 92, "name": "93", "position": 1, "description": "Afghanistan" }, { "id": 93, "name": "355", "position": 2, "description": "Albania" }, { "id": 94, "name": "213", "position": 3, "description": "Algeria" }, { "id": 95, "name": "1-684", "position": 4, "description": "American Samoa" } ] gender = [ { "id": 1, "name": "Female" }, { "id": 3 "name": "Male" } ] The dataframe should have two columns: Gender and Country Code. The values for gender will be from the gender variable while the value for country code will be from the country code variable. I have tried: df = pd.DataFrame(list( zip( gender, country_codes ) ), columns=[ "name" "description" ] ).rename({ "name": "Gender", "description": "Country" })) writer = pd.ExcelWriter('my_excel_file.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name="sample_sheet", index=False) writer.save() But after running the script, the excel file was not populated. -
How to get reference table fields with django model query
When I am trying to fetch foreign key table using django model I am only unable to get the referenced table details. I have two models TblVersion and TblProject defined below class TblVersion(models.Model): version_id = models.AutoField(primary_key=True) project = models.ForeignKey(TblProject, models.DO_NOTHING) version_major = models.PositiveSmallIntegerField() version_minor = models.PositiveSmallIntegerField() class Meta: managed = False db_table = 'tbl_version' class TblProject(models.Model): project_id = models.AutoField(primary_key=True) project_name = models.CharField(max_length=32) class Meta: managed = False db_table = 'tbl_project' My current code implementation: result= TblVersion.objects.all().select_related() data = serializers.serialize('json', result) print(data) Code Result: `[{"model": "CCM_API.tblversion", "pk": 1, "fields": {"project": 1, "version_major": 1000, "version_minor": 0}}, {"model": "CCM_API.tblversion", "pk": 2, "fields": {"project": 2, "version_major": 1000, "version_minor": 0}}, {"model": "CCM_API.tblversion", "pk": 3, "fields": {"project": 2, "version_major": 1000, "version_minor": 2}}]` The code output lacks the foreign key fields (Project Name). I want a list of version numbers with their respective projects like this. | Version Id | Major Version | Minor Version | Project Id | Project Name| | -------- | -------- |-------- |-------- |-------- | | 1 | 1000 |1 | 1| PROJ_1 | | 2 | 1000 |1 | 2| PROJ_2 | | 3 | 1000 |2 | 1| PROJ_1 | -
Django can not connect to PostgreSQL DB
When I`m trying to connect Django Server to PostgreSQL db there is an error: " port 5433 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? " I`m using Windows 10, Pycharm, Debian Settings in Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'ps_store_db', 'USER': 'zesshi', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5433', } } Tried to check connection with DBeaver and all`s good there, but still cant connect with Django Dbeaver connection My firewall is off, i was trying to change from 5432 to 5433 -
Django query to return percentage of a users with a post
Two models Users (built-in) and Posts: class Post(models.Model): post_date = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='user_post') post = models.CharField(max_length=100) I want to have an API endpoint that returns the percentage of users that have posted. Basically I want SUM(unique users who have posted) / total_users I have been trying to play around with annotate and aggregate, but I am getting the sum of posts for each users, or the sum of users per post (which is one...). How can I get the sum of posts returned with unique users, divide that by user.count and return? I feel like I am missing something silly but my brain has gone to mush staring at this. class PostParticipationAPIView(generics.ListAPIView): queryset = Post.objects.all() serializer_class = PostSerializer def get_queryset(self): start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') # How can I take something like this, divide it by User.objects.all().count() * 100, and assign it to something to return as the queryset? queryset = Post.objects.filter(post_date__gte=start_date, post_date__lte=end_date).distinct('user').count() return queryset My goal is to end up with the endpoint like: { total_participation: 97.3 } Thanks for any guidance. BCBB -
DJango How to select certain item from database table in html
I have a store page that gets entries from a Products table. This shows products in order in the same format infinitely for how many are in the table. ` {% for product in products %} <div class="container2"> <div href="item" class= 'product-item'> <div class= 'image-cont'> <a href="item"><img class='product-image'src = '{{product.product_picture.url}}' alt="" ></a> </div> {% if product.offer != 0 %} <div class= 'offer-banner' > <a href="item">Special Offer</a> </div> {% endif %} </div> <div href="item" class="product-content"> <div href="item" class="product-title"> <a href="item" >{{product.name}}</a> </div> <div class="product-price"> <a href="item" >${{product.price}}</a> </div> <br> <div class="product-desc"> <a href="item" >{{product.desc}}</a> </div> <br> <div class="product-userpfp"> <a href="#" ><img src='{{product.userpfp.url}}'></a> </div> <br> <div class="product-poster-name"> <a href="#" >{{product.username}}</a> </div> <br> </div> </div> </div> </div> {% endfor %} ` I want to be able to click on any product from products and get a page with the specific item I clicked on. This is my Item page. ` {`% extends 'base.html' %} {% load static %} {% block css %} <link rel="stylesheet" href= "{% static 'css\item.css' %}" > {% endblock %} {%block content%} {% load static %} <h1>Item</h1> <h3>{{item.name}}</h3> {% endblock %}` ` The problem should be inside the view.py file ` def item(request): item = Product.objects.select_related() return render(request, "item.html", {"item": … -
createsuperuser is not working with custom user model
I know this question is a repeat (I've looked at similar posts here and here although the I still couldn't anywhere with the solutions. I've created a custom user model for my application but when I create a superuser I can't seem to sign in on the admin panel. What have I done wrong? user model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must provide an email to create an account') if not username: raise ValueError('Users must provide a username to create an account') user = self.model( email=self.normalize_email(email), username=username ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last_login', auto_now_add=True) is_admin = models.BooleanField(default=True) is_active = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserAccountManager() def __str__(self): return f'email: {self.email}\nusername: {self.username}' def has_perm(self, perm, obj=None): return self.is_admin def has_module_perm(self, app_label): return True my settings from pathlib import Path # Build paths inside the project like … -
How do I make a post request work after using get_queryset?
I would like to have a list of a user's devices with a checkbox next to each one. The user can select the devices they want to view on a map by clicking on the corresponding checkboxes then clicking a submit button. I am not including the mapping portion in this question, because I plan to work that out later. The step that is causing problems right now is trying to use a post request. To have the user only be able to see the devices that are assigned to them I am using the get_queryset method. I have seen a couple questions regarding using a post request along with the get_queryset method, but they do not seem to work for me. Using the view below, when I select a checkbox and then click submit, it looks like a post request happens followed immediately by a get request and the result is my table is empty when the page loads. Portion of my views.py file: class DeviceListView(LoginRequiredMixin, ListView): model = Device template_name = 'tracking/home.html' context_object_name = 'devices' # ordering = ['-date_added'] def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs).filter(who_added=self.request.user) def post(self, request): form = SelectForm(request.POST) # if form.is_valid(): # text = … -
Foreign Key Constraint Failed Django with UUID
Trying to save to a table with a foreign key but come up with a IntegrityError: Foreign Key Constraint failed. I have checked to make sure I am getting the correct data for my foreign key and it seems to be there. I am not sure why I am getting this error. Models.py class IPHold(models.Model): uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) CHOICES = [ ('1', 'Book'), ('2', 'Documentary'), ('3', 'Graphic Novel/Comic'), ('4', 'Journalism'), ('5', 'Merchandise'), ('6', 'Podcast'), ('7', 'Stage Play/Musical'), ('8', 'Video Game'), ] media_type = models.CharField(max_length=1, choices=CHOICES, blank=False) title = models.CharField(max_length=255, blank=False) author_creator = models.CharField(max_length=255, blank=True) production_company = models.CharField(max_length=255, blank=True) class RoleHold(models.Model): ip = models.ForeignKey(IPHold, on_delete=models.CASCADE, related_name='ip_role') name = models.CharField(max_length=128, blank=False) TYPE = [ ('1', 'Lead'), ('2', 'Supporting'), ] role_type = models.CharField(max_length=1, choices=TYPE, blank=True) age_min = models.PositiveSmallIntegerField(blank=True) age_max = models.PositiveSmallIntegerField(blank=True) ETHNICITY = [ ('1', 'American Indian or Alaska Native'), ('2', 'Asian'), ('3', 'Black or African American'), ('4', 'Hispanic or Latino'), ('5', 'Native Hawaiian or Other Pacific Islander'), ('6', 'White'), ('7', 'Unknown/Irrelevant'), ] race = models.CharField(max_length=1, choices=ETHNICITY, blank=True) GENDEROPTIONS = [ ('1', 'Male'), ('2', 'Female'), ('3', 'N/A'), ('4', 'Unknown/Irrelevant'), ] gender = models.CharField(max_length=1, choices=GENDEROPTIONS, blank=True) description = models.TextField(blank=True) Views.py def add_characters(request): id = request.GET.get('id') ips = IPHold.objects.get(uuid=id) form = forms.AddCharacter context … -
local variable 'product' referenced before assignment
I am trying to create a django view which will let users to create a new product on the website. class CreateProductView(APIView): serializer_class = CreateProductSerializer def post(self, request, format = None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): name = serializer.data.name content = serializer.data.content category = serializer.data.category product = Product(name=name, content=content, category=category) product.save() return Response(ProductSerializer(product).data, status=status.HTTP_201_CREATED) But it is giving this error: UnboundLocalError at /api/create-product local variable 'product' referenced before assignment Request Method: POST Request URL: http://127.0.0.1:8000/api/create-product Django Version: 4.0.5 Exception Type: UnboundLocalError Exception Value: local variable 'product' referenced before assignment Exception Location: H:\Extension Drive (H)\My Software Applications\DeCluttered_Life\declutterd_life\api\views.py, line 42, in post Python Executable: C:\Python310\python.exe Python Version: 3.10.5 Python Path: ['H:\\Extension Drive (H)\\My Software ' 'Applications\\DeCluttered_Life\\declutterd_life', 'C:\\Python310\\python310.zip', 'C:\\Python310\\DLLs', 'C:\\Python310\\lib', 'C:\\Python310', 'C:\\Python310\\lib\\site-packages'] Server time: Fri, 02 Dec 2022 17:26:24 +0000 I tried to look other issues similar to this, but couldn't find the solution. -
Ignore a line of Javascript if the element isn't present on the page and skip to the next line?
Working on a django web app and running into an issue with my javascript. The web application is multiple different html pages, so the elements my js code is searching for are present on some pages but not others. If the second line is not present on the current page, the script stops running and the final function will not work. I have a "plan" page where you can add additional tags to your plan and then a separate page to filter results. If I'm on the plan page then the "#filterBtn" element is not present so my createNewTagField function doesn't work. If I switch the two lines of code, the opposite happens. I can't get them both to work since the elements javascript is searching for are on two different pages and not present at the same time. These are the lines causing problems. document.addEventListener('DOMContentLoaded', function() { document.querySelector('#mobile-menu').onclick = toggleMobileMenu; document.querySelector('#filterBtn').onclick = toggleFiltersMenu; document.querySelector('#addTag').onclick = createNewTagField; }); I've rearranged the lines of code and it just fixes it for one page while still having the problem on the other page. I'm thinking it needs to be something like if null then continue to the next line, but haven't been … -
Does OpenXML SDK only work with Visual Studio?
I am creating a Django application to be run on an IIS server. I need to update an Excel file automatically on the server. Given that the interactive update using COM (pywin32.com) is not supported by Microsoft (https://support.microsoft.com/en-us/topic/considerations-for-server-side-automation-of-office-48bcfe93-8a89-47f1-0bce-017433ad79e2) I need to use the Microsoft recommended approach which involves using OpenXML SDK. In the following link, https://learn.microsoft.com/en-us/office/open-xml/getting-started, it mentions this is used with Visual Studio. My question is whether this is the only way of using OpenXML SDK to edit Office documents. I do not use Visual Studio. Thank you for any help provided I have searched the internet but have not found a suitable answer.