Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why isinstance(Test(), MyAbstractClass) return False even if I implement all abstract methods in Test class
From some book, it says when we define a class and implement all abstract methods, even if the class is not inherited from abstract class, the isinstance() check will return True. I try it on my local: from collections import abc class Test: def __len__(self): return 0 print(isinstance(Test(), abc.Sized)) Because there is only one abstract method in abc.Sized class:_len_, the output is True as expected. But when I try to define my own abstract class, it fails: from abc import abstractmethod, ABCMeta Class MyAbstractClass(metaclass=ABCMeta): @abstractmethod def get_size(self):pass class Test: def get_size(self): return 0 print(isinstance(Test(), MyAbstractClass)) The output is False. I need to register it if I want it to be True: MyAbstractClass.register(Test) Why? Why I check it with abs.Sized I don't need to register it but with my own defined abstract class, I have to register it? -
User Roles In Django
I was able to build a Web app that can restrict access to certain pages for authenticated using Django permissionmixedin But I want to divide authenticated users into groups that can be able to access only certain pages. That is even if you are authenticated you can't access all the pages, but can only access the pages that your group fall into. I thought I could set that up when I log into Django admin panel as a super user, but it did not work. Please I need a comprehensive guide on how to do that, both on the user model, views.py and any other file. Because am completely new to this. Am using class based views because am not conversant with function based views. -
loop through two lists of lists and extract elements
I have two lists: list_a contains the number of questions and types I want. There are three types 1* 2* 3* list_b contain all the questions and the types eg 'Q1:1*' and 'Q1 is of type 1*' is considered one question.. So far I have managed to write a code that loops through and randomly selects the number of questions and the type I want. import random list_a = [[1, 1, 1]] # Read this as i want 1 question of type 1*, 1 question of type 2* and 1 question of type 3* list_b = [['Q1:1*','Q1 is of type 1*', 'Q2:1*', 'Q2 is of type 1*', 'Q3:2*', 'Q3 is of type 2*', 'Q4:2*','Q4 is of type 2*', 'Q5:3*', 'Q5 is of type 3*', 'Q6:3*', 'Q6 is of type 3*']] result = [] # Iterate over each type of question in list_a for i in range(len(list_a[0])): # Determine the number of questions required for this type num_questions = list_a[0][i] # Create a list of the indices of questions in list_b that match this type question_indices = [idx for idx, q in enumerate(list_b[0]) if f":{i+1}*" in q] # Randomly select the required number of questions and their corresponding elements selected_indices = … -
Use xml.etree.elementtree to process xml with xmlns="http://www.w3.org/2005/Atom"
I'm trying to process the data extracted from the web. The decoded raw data was bytes of xml file. I had some old code that just magically worked. However, I'm not sure what they were doing since it's been a while. import urllib, urllib.request url = 'http://export.arxiv.org/api/query?search_query=all:electron+OR+query?id_list=hep-th/9112001&start=0&max_results=2' data = urllib.request.urlopen(url) which could be decoded with data.read().decode('utf-8') which had a file of the form <?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <link href="http://arxiv.org/api/query?search_query%3Dall%3Aelectron%20OR%20query%3Fid_list%3Dhep-th%2F9112001%26id_list%3D%26start%3D0%26max_results%3D2" rel="self" type="application/atom+xml"/> <title type="html">ArXiv Query: search_query=all:electron OR query?id_list=hep-th/9112001&amp;id_list=&amp;start=0&amp;max_results=2</title> <id>http://arxiv.org/api/hNIXPXLfJXds3VmSJQ2mnDpmElY</id> <updated>2023-03-20T00:00:00-04:00</updated> <opensearch:totalResults xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">194139</opensearch:totalResults> <opensearch:startIndex xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">0</opensearch:startIndex> <opensearch:itemsPerPage xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">2</opensearch:itemsPerPage> <entry> <id>http://arxiv.org/abs/cond-mat/0102536v1</id> <updated>2001-02-28T20:12:09Z</updated> <published>2001-02-28T20:12:09Z</published> <title>Impact of Electron-Electron Cusp on Configuration Interaction Energies</title> <summary> The effect of the electron-electron cusp on the convergence of configuration interaction (CI) wave functions is examined. By analogy with the pseudopotential approach for electron-ion interactions, an effective electron-electron interaction is developed which closely reproduces the scattering of the Coulomb interaction but is smooth and finite at zero electron-electron separation. The exact many-electron wave function for this smooth effective interaction has no cusp at zero electron-electron separation. We perform CI and quantum Monte Carlo calculations for He and Be atoms, both with the Coulomb electron-electron interaction and with the smooth effective electron-electron interaction. We find that convergence of the CI expansion … -
How to create upload method with authentication FastAPI Users
router = APIRouter( prefix='/reglaments', include_in_schema=True ) router.include_router(reglament_router, dependencies=[Depends(current_user)]) In the route I added dependencies to authentication from FastAPI Users from fastapi_users import FastAPIUsers ... ... ... current_user = fastapi_users.current_user() Below example of how implemented my method @router.post('/{id}/upload', status_code=status.HTTP_200_OK) async def upload_files( relgament_id: int = Path(alias='id'), files: List[UploadFile] = File(description='Reglament documents (pdf, word, excel, etc.)')): '''Upload Reglament Files''' PATH = './static/reglaments' if not os.path.exists(f'{PATH}/{relgament_id}'): path = os.path.join(f'{PATH}/', f'{relgament_id}') try: os.mkdir(path) print(f'[+] Created new directory {relgament_id}, by path {PATH}') except: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Can't create new directory by path {path}") for file in files: try: async with aiofiles.open(f'{PATH}/{relgament_id}/{file.filename}', 'wb') as f: while content := await file.read(1024 * 1024): f.write(content) except: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='There was an error uploading the file') finally: file.file.close() return {"message": "Successfully uploaded"} but when run this method gives 422 error { "detail": [ { "loc": [ "body", "files" ], "msg": "field required", "type": "value_error.missing" } ] } How to implement upload method with authenctication dependecies from FastAPI Users module -
What is the difference between a Python tuple and a Python list? [duplicate]
I am currently learning about python lists and python tuples. My teacher asked me to list out the differences of the list and the tuple. Can anyone help? -
Python - check if condition is met within a given timeout
I've a script that 1. downloads & push binaries to internal registry (func_to_push_image) and 2. process messages from a section of messaging queue, to see if the push is successful by filtering the messages for a keyword 3. If the push is successful, monitor and process another section of messaging queue, to validate whether those two binaries are installed by looking at the install_status keyword. Timeout for the push action is 2 mins, else fail the script immediately. Timeout for the install action is 1 min, else fail the script with timeout. Messaging queue's output for the binaries installations looks like below. { "location": "root", "md5":"a3288ec45c8d159fbb656972eb4cdfg84jsfbsdf", "fireEye":"v3", "Binaries":[ A:{ "name":"HP-Protect", "version": "v1.3", "effect": "NIL", "install_status":"On Going", } B:{ "name":"Covertur", "version": "v1.0", "effect": "NIL", "install_status":"Installed" }] } Redacted code: registry_timeout = 2 install_timeout = 1 Other variables holding server and partition details. def get_info_from_messaging_queue(server, broker): depending on the partition, returns the messages from the messaging queue. def func_to_push_image(): logic to upload the artifact to the registry. def func_to_check_status_of_installed_binaries(): #This function should Ideally check the status of both binaries has been "Completed" status = False install_status = get_info_from_messaging_queue(server, broker) if install_status['Binaries'][A]['install_status'] == "Completed" and install_status['Binaries'][B]['install_status'] == "Completed": status = True return status … -
Hide Unsupported operand type(s) for -: 'int' and 'NoneType' when no data in database
I am having this issue where I get this error unless there are at least 2 lines of data in the database. Basically what I am doing is marking an item as refunded. I will aggregate all of the fields and then do the math. If I do not have at least 2 lines of data in the database, I always get this error. unsupported operand type(s) for -: 'int' and 'NoneType' The specific line is throwing the error is: total_partial = 0 - total_p_r['refund_amount__sum'] I am not understanding why I am getting NoneType when the default is set to zero on all lines of the models. The code is below. views.py def inventory_management_refund(request): inventory = Inventory.objects.filter(Q(status__contains='REFUNDED') | Q(status__contains='Partial Refund')).order_by('id') totals = Inventory.objects.filter(status__contains='REFUNDED').aggregate( Sum('paid'), Sum('soldprice'), Sum('shipcost'), ) total_p_r = Inventory.objects.filter(status__contains='Partial Refund').aggregate( Sum('refund_amount') ) total_full = 0 - totals['paid__sum'] - totals['soldprice__sum'] - totals['shipcost__sum'] total_partial = 0 - total_p_r['refund_amount__sum'] total_refund_loss = total_full + total_partial return render(request, 'inventory/refunds.html', {"inventory": inventory, "total_refund_loss": total_refund_loss}) template.html <div> <div> <h1 class="text-center">Refunded Items</h1> <hr> </div> {% if inventory.count == 0 %} <h2 class="text-success text-center">There are currently no refunds!</h2> {% endif %} {% if inventory.count > 0 %} <table class="table table-striped"> <thead> <tr> <th>Product</th> <th>Description</th> <th class="invmanrow">Purchase Price</th> <th … -
Label with text copy functionality creation in tkinter
I've got the following tkinter classes that give copy/paste functionality to Entries and copy functionality to Labels. However, I'm not sure how to get the CPLabel class to retrieve the text from the text parameter. When I run the program as is, the CPLabel is packed as evidenced by a space where it should appear, however, no text shows. class CPEntry(Entry): def __init__(self, *args, **kwargs): Entry.__init__(self, *args, **kwargs) self.bind('<Control-c>', self.copy) self.bind('<Control-v>', self.paste) def copy(self, event): self.clipboard_clear() selected_text = self.selection_get() self.clipboard_append(selected_text) def paste(self, event): self.delete(0, END) pasted_text = self.clipboard_get() self.insert(0, pasted_text) class CPLabel(CPEntry): def __init__(self, *args, **kwargs): CPEntry.__init__(self, *args, **kwargs) self.configure(state="readonly", highlightthickness=0, bd=0, cursor="arrow", textvariable=None) self.insert(0, kwargs.get('text', '')) The text that should be displayed is what is within the text parameter. For example, the CPLabel below should display 'Enter a prime number for the value of p'. pLabel = CPLabel(root, text = 'Enter a prime number for the value of p') If you could let me know what I'm doing wrong, or how to get this to work properly that would be awesome. Thanks. -
How to make our program run when my raspberry pi boot up? either using Cron or rc.local
I want to send data from the sensor to the database using raspberry pi. The database is the raspberry pi itself. This is the code I want to run. import time import mysql.connector from bmp280 import BMP280 from datetime import datetime # DATABSE VARIABLE DBHOST = "localhost" #The Host use "localhost" or the database IP DBUSER = "ISTTS" #The user DBPASS = "digital123" #The user password DBDATA = "exampledb" #The database to insert DBTABL = "Test2" #The table to insert # DEVICE ID (int) DID = 1 # SENSOR DELAY DELAY = 5 try: from smbus2 import SMBus except ImportError: from smbus import SMBus mydb = mysql.connector.connect(host=DBHOST, user=DBUSER, password=DBPASS, database=DBDATA) mycursor = mydb.cursor() # Initialise the BMP280 bus = SMBus(1) bmp280 = BMP280(i2c_dev=bus) while True: now = datetime.now() temperature = round(bmp280.get_temperature(),2) pressure = round(bmp280.get_pressure(),2) print('{}*C {}hPa'.format(temperature, pressure)) time.sleep(DELAY) sql = "INSERT INTO " + DBTABL + " (Date, DeviceID, Temperature, Pressure) VALUES (%s, %s, %s, %s)" val = (now, DID, temperature, pressure) mycursor.execute(sql, val) mydb.commit() I tried to use cron before, but somehow it didn't work. What i put in my Cron is @reboot sudo python3 /home/istts/Desktop/MySQL.py I tried to see the log but didn't find anything related to my … -
why does function does not stop when a exception is raised (Python)
I have a class like this: import threading import time import psutil class TimeoutError(Exception): pass class Performance: def __init__(self, func, time_limit=20, except_return = None) -> None: self.func = func self.except_return = except_return start_time = time.perf_counter() process = psutil.Process() process.memory_info().rss process.memory_info().rss elapsed_time = time.perf_counter() - start_time self.time_limit = time_limit + elapsed_time self.__init_time_waste = elapsed_time def handler(self): with open('Output.txt',mode='a',encoding='utf-8') as f: f.writelines("Time Limited Exceeded!\n") raise TimeoutError("Time Limited Exceeded!") def run(self): def run_func(): timer = threading.Timer(self.time_limit,self.handler) result = [] start_time = 0 before_memory = 0 after_memory = 0 elapsed_time = 0 timer.start() try: start_time = time.perf_counter() process = psutil.Process() before_memory = process.memory_info().rss result = self.func() after_memory = process.memory_info().rss elapsed_time = time.perf_counter() - start_time - self.__init_time_waste except Exception as e: print(e) timer.cancel() return self.except_return else: timer.cancel() with open('Output.txt',mode='a',encoding='utf-8') as f: f.writelines(f"Executing Time: {elapsed_time:.5f} \n") f.writelines(f"Memory Used: {after_memory - before_memory} bytes \n") print(f"Executing Time: {elapsed_time:.5f}") print(f"Memory Used: {after_memory - before_memory} bytes") return result return run_func() This class is used to limit the run time of a function and compute the memory used. But when the exception is raised, the self.func still execute and doesn't terminated. Please help me :((( -
How to create a stub Python package for PyCharm?
Let's say we have a builtin module car. We have no autocomplete in PyCharm for it. It has interface: def getState(id, optional_id = None): pass def log(value): pass So, end usage would be: import car car.getState(5) car.log('Test') How to create a package and join it into PyCharm to make autocomplete work for a described interface? If I created a package car-stub with car.py file, and installed it in the project, I will have to use code line from car-stub import car. But how to make it in such a way it would not require code changes? The system would provide autocomplete for import car. -
Django backend server runtime error using gunicorn
I developed backend server using django python framework. But, It didn't work. I have searched this error in websites, but I couldn't find answer. Here is error log: 11:58:38 master systemd[1]: Starting Gunicorn Service... 11:58:38 master systemd[1]: Started Gunicorn Service. 11:58:38 master gunicorn[2705621]: [2023-03-20 11:58:38 +0900] [2705621] [INFO] Starting gunicorn 20.1.0 11:58:38 master gunicorn[2705621]: [2023-03-20 11:58:38 +0900] [2705621] [INFO] Listening at: http://127.0.0.1:8001 (2705621) 11:58:38 master gunicorn[2705621]: [2023-03-20 11:58:38 +0900] [2705621] [INFO] Using worker: eventlet 11:58:38 master gunicorn[2705626]: [2023-03-20 11:58:38 +0900] [2705626] [INFO] Booting worker with pid: 2705626 11:59:08 master gunicorn[2705621]: [2023-03-20 11:59:08 +0900] [2705621] [CRITICAL] WORKER TIMEOUT (pid:2705626) 11:59:08 master gunicorn[2705626]: Stack trace (most recent call last): 11:59:08 master gunicorn[2705626]: #16 Object "[0x7fd822b8c5b7]", at 0x7fd822b8c5b7, in 11:59:08 master gunicorn[2705626]: #15 Object "/home/master/envs/guide/lib/python3.8/site-packages/greenlet/_greenlet.cpython-38-x86_64-linux-gnu.so", at 0x7fd907a96cbf, in greenlet::UserGreenlet::g_switch() 11:59:08 master gunicorn[2705626]: #14 Object "/home/master/envs/guide/lib/python3.8/site-packages/greenlet/_greenlet.cpython-38-x86_64-linux-gnu.so", at 0x7fd907a969a1, in greenlet::UserGreenlet::g_initialstub(void*) 11:59:08 master gunicorn[2705626]: #13 Object "/home/master/envs/guide/lib/python3.8/site-packages/greenlet/_greenlet.cpython-38-x86_64-linux-gnu.so", at 0x7fd907a95a16, in greenlet::UserGreenlet::inner_bootstrap(greenlet::refs::_OwnedGreenlet<_greenlet, &greenlet::refs::GreenletChecker>&, greenlet::refs::OwnedReference<_object, &greenlet::refs::NoOpChecker>&) 11:59:08 master gunicorn[2705626]: #12 Object "/home/master/envs/guide/bin/python", at 0x5f52b1, in PyObject_Call 11:59:08 master gunicorn[2705626]: #11 Object "/home/master/envs/guide/bin/python", at 0x50b32b, in 11:59:08 master gunicorn[2705626]: #10 Object "/home/master/envs/guide/bin/python", at 0x5f60c2, in _PyFunction_Vectorcall 11:59:08 master gunicorn[2705626]: #9 Object "/home/master/envs/guide/bin/python", at 0x569d89, in _PyEval_EvalCodeWithName 11:59:08 master gunicorn[2705626]: #8 Object "/home/master/envs/guide/bin/python", at 0x56bbe0, in _PyEval_EvalFrameDefault 11:59:08 master … -
JSONDecodeError Expecting value: line 1 column 1 (char 0) when receiving via Bluetooth
I am transmitting a JSON payload from an Arduino microcontroller and attempting to receive it using a Python script: import bluetooth #pybluez import json sensor_address = "18:D9:31:YY:C7:4A" socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) socket.connect((sensor_address, 1)) buffer = "" print("Listening...") while True: data = socket.recv(1024) buffer += str(data, encoding='ascii') print(buffer) # used to check json payload try: data = json.loads(buffer) print("Received:", data) buffer = "" except json.JSONDecodeError as e: print(e) continue Examining the value stored in buffer before entering the try statement, I see what appears to be perfectly valid JSON: {"a_x":957.5195,"a_y":-0.488281,"a_z":315.918,"g_x":-0.625954,"g_y":-1.305344}{"a_x":961.914,"a_y":-1.953125,"a_z":297.8516,"g_x":-2.816794,"g_y":2.572519}{"a_x":964.8437,"a_y":3.417969,"a_z":303.2227,"g_x":-1,"g_y":0.374046} However the result of my script is only Expecting value: line 1 column 1 (char 0) repeatedly. Why doesn't the code inside the try statement execute once a complete payload has been received? My hunch is that at no time does a valid JSON payload appear in buffer, but instead valid payloads appear along with incomplete payloads. Is it possible to use a regular expression to extract a valid payload from a string? -
why iam run "make" command to install tlwn722n driver, and error at "prandom_u32" [closed]
why iam run "make" command to install tlwn722n driver, and error at "netif_napi_add" cd rtl8188eus make <<ERROR make install -
¿How to config WAF to API GATEWAY/LAMBDA with serverless framework?
I need set a AWS WAF to AWS API GATEWAY with serverless framework. I tried with this plugin (https://www.serverless.com/plugins/serverless-associate-waf) but don't work. I added this code with serverless.yml : plugins: - serverless-associate-waf - serverless-plugin-bind-deployment-id custom: associateWaf: name: Development-waf version: V2 #(optional) Regional | V2 but when I launch deploy, this return an error: Error: The CloudFormation template is invalid: Unresolved resource dependencies [ApiGatewayRestApi] in the Outputs block of the template -
python GIL: Why need Lock when making changes to collections?
Sorry one question, everyone knows Python has GIL, so only one thread is spinning at any one point in time. https://opensource.com/article/17/4/grok-gil This said, then why do we need lock when accessing/modifying collections? Appending or popping elements from a list for example. Or updating a dictionary? Operations like list.sort() also is atomic. I am guessing the answer be: Are you sure any of the operations that you're performing is "Atomic"? If not it can be pre-empted (Preemptive multi-tasking) Thus, in general, because you're unsure how things are implemented under-the-hood, safer to just lock.acquire? Thanks in advance. -
Django Channels AsyncWebsocketConsumer render template
I am trying to send HTML over a websocket via Django channels. It worked fine with a non-asynchronous Websocket Consumer, but upon converting everything to Async I am left with this last error. Here is the problematic code segment and error message: context = { "online_users": redis_instance.smembers(redis_online_name) } await self.channel_layer.group_send( self.room_group_name, { 'type': 'online_users_list', 'html': render_to_string("partials/message/hx_online_users.html", context), } ) server ERROR Exception inside application: 'coroutine' object is not iterable Traceback (most recent call last): File "/.../python3.11/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/middleware.py", line 24, in __call__ return await self.inner(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/routing.py", line 116, in __call__ return await application( ^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/.../python3.11/site-packages/channels/consumer.py", line 58, in __call__ await await_many_dispatch( File "/.../python3.11/site-packages/channels/utils.py", line 50, in await_many_dispatch await dispatch(result) File "/.../python3.11/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/.../python3.11/site-packages/channels/generic/websocket.py", line 173, in websocket_connect await self.connect() File "/.../chat/consumers.py", line 63, in connect 'html': render_to_string("partials/message/hx_online_users.html", context), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File … -
Writing an asynchronous view function in django for my form
I want to write an async function in django. My view is the same for my GET request and for my POST request (form). My goal is to make my POST asynchronous, so when I send my form, the page does not remain loading and waiting for the server's response. In my POST request I send my form data to an API so I want this function in a coroutine, but it's not working properly. I'm using uvicorn to run my application with the default asgi configuration. I will put my view and my api function here: async def payment_return_view(request): if request.method == 'POST': # do process form form = PaymentReturnForm(request.POST) if form.is_valid(): payment = get_payment_return_api_data(form) # perform request to payment return through API r = await asyncio.gather(*[payment_return(payment)]) request.session[payment.returnID] = r.dict() return redirect("payment_return_result", internal_id=payment.returnID) else: # get params from request params = request.GET payments = get_payments(params).dict() payments = payments.get('entries', []) form = PaymentReturnForm() context = { 'form': form, 'payments': payments, 'params': params } return render(request, 'payment-return.html', context) And this is my async funtion: async def payment_return(payment_return: PaymentReturn) -> Result: d = payment_return.dict() async with aiohttp.ClientSession() as session: async with session.post( f"{API_URL_BASE}/payment/return", data=json.dumps(d, cls=DjangoJSONEncoder), headers={'Content-Type': 'application/json'} ) as r: data = … -
Get the string in an span id tag, wehn running python selenium
I want to extract the word "In stock" from the element. The tag looks like this: <span id="quantitySpan">" in stock" <img class="quantitySpanImg" src="https://d3m9l0v76dty0.cloudfront.net/system/photos/436808/original/34f362ca4ecee94ab2262e159a8ce432.jpg?1588592491"> <-span> I tried to get the string using: driver.find_element(By.ID, "quantitySpan") but it didn't work. I tried by XPath but I'm still not getting the string. driver.find_element(By.XPATH,"/html/body/div[4]/div[2]/div/form/div[2]/div[1]/div[2]/div[2]/span") -
Python, How can I dynamically define a variable when it is imported
I don't actually know if this is possible but I would like to do the following: foo.py: # foo.py my_var = "hello_world" def fancy(s): return s.replace("_"," ").replace("hello", "Hola") main.py: # main.py from foo import my_var, my_var_fancy print(my_var) print(my_var_fancy) And get an output like: >> hello_world >> Hola world Note that I do not want to explicitly define "my_var_fancy" anywhere. I would like I to be dynamically defined when imported using the fancy function. I suspect this could possibly be accomplished with decorators or something similar to a hasattr() check on the module but I'm not sure how. -
Password reset confirm/Password reset request-Django Rest api
I am trying to make reset password functionality.I am able to make the password reset request as I receive the user email for which password need to be changed and successfully send the user the email to reset it(via postman).The problem is when I open the reset mail it directs to the password reset confirm where the user enter the new password to replace the old it in the database.I am unable to handle it with both the GET and POST methods.GET is to display the field where user can enter the new password and POST for posting the request and updating the custom user model. serializers.py from rest_framework import serializers from django.contrib.auth.hashers import make_password from .models import CustomUser class SignUpUserSerialzer(serializers.ModelSerializer): password = serializers.CharField(max_length=100, write_only=True) def validate_password(self, password): return make_password(password) class Meta: model = CustomUser fields = '__all__' class ChangePasswordSerializer(serializers.Serializer): model = CustomUser """ password = serializers.CharField(max_length=100, write_only=True) def validate_password(self, password): return make_password(password) class Meta: model = CustomUser fields = ['password'] urls.py from django.urls import path,include from . import views # from .views import ChangePasswordView urlpatterns = [ path('register/', views.register, name='register'), path('login/', views.custom_login, name='login'), path('logout/', views.custom_logout, name='logout'), path('user/', views.user_profile, name='user_profile'), path('activate/<uidb64>/<token>', views.activate, name='activate'), path("passwordreset/", views.password_reset_request, name="password_reset"), path('reset/<uidb64>/<token>/', views.passwordResetConfirm, name='password_reset_confirm'), ] … -
Django limit records (options) for ModelChoiceField
I have a Model Reader with ModelChoiceField favourite_book which is a Foreign key. It is a DropDown menu and user can choose one from 40.000 possible options (records in the database). There is a problem when editing this Model object and this specific field because DropDown is being populated with all the records from the database which takes too much time and memory. So, I have to find a way to somehow render this field with a matching option (that user has previously selected and saved in DB) alone and not with thousands of other options. I tried: readerForm.fields['books'].initial = Books.objects.get(id=url) but initial doesn't work with bound forms. I have $.ajax request that will later filter those 40.000 options based on input so user can choose some other option if needed. -
Url not found on ajax reqest Django
I want to trigger on update view via ajax call but showing the URL is not found. Any help would be appreciated Ajax: $(document).on("change", "#id_device_type", function() { var id = $(this).val(); $.ajax({ url: '/register-non-device/view/', type: "GET", dataType: 'json', data: $(this).val() }); }); url: path('register-non-device/view/<int:pk>/', RegisterNonDeviceView.as_view(), name='register-non-device') View: class RegisterNonDeviceView(UpdateView): model = AnticipatedNonDevice form_class = AnticipatedNonDeviceForm template_name = 'anticipated_non_device.html' success_url = reverse_lazy('app:po-search-non-device') -
I am trying to calculate the product price before the discount
I am trying to calculate the product price before the discount through the product price and the discount percentage The question is: how do I write this equation price / (1-discount%) into the template in Django Example: <span class="old-price">{{......}} L.E</span> <span class="old-price">{{......}} L.E</span>