Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django deploy nginx auto log out
I am experiencing an issue with my Django application where I am automatically logged out when trying to access my admin panel. I suspect that the problem may be related to session preservation. To further investigate, I have included my nginx configuration and my Django settings file below. map $sent_http_content_type $expires { default off; text/html epoch; text/css max; application/javascript max; ~image/ max; } server { listen 80; listen [::]:80; server_name www.khalimbetovulugbek.com khalimbetovulugbek.com; return 301 https://khalimbetovulugbek.com; } server { listen 443 ssl http2; ssl_certificate /etc/nginx/ssl/server.crt; ssl_certificate_key /etc/nginx/ssl/server.key; server_name khalimbetovulugbek.com www.khalimbetovulugbek.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/benku/portfolio/src; } location /media/ { root /home/benku/portfolio/src; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } expires $expires; }``` and is it correct location for media file? seems like my session is not preserved and that is why i am logging out settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Connection to Postgresql server on socket "/var/run/postgresql/.s.PGSQL.5432" failed. OperationalError on railway.app
I deployed my Django app on railway.app recently. After deployment, I tried to login into my app when I was confronted by this OperationalError. The Traceback looks something like this: Environment: Request Method: POST Request URL: http://optimuscore.up.railway.app/ Django Version: 4.0 Python Version: 3.10.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account', 'dhule', 'solapur', 'mathfilters', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/opt/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection self.connect() File "/opt/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/opt/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 211, in connect self.connection = self.get_new_connection(conn_params) File "/opt/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/opt/venv/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 199, in get_new_connection connection = Database.connect(**conn_params) File "/opt/venv/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) The above exception (connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? ) was the direct cause of the following exception: File "/opt/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/opt/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/accounting/account/views.py", line 72, in login print('fm: ', fm) File "/opt/venv/lib/python3.10/site-packages/django/forms/utils.py", line 55, in render context or self.get_context(), File "/opt/venv/lib/python3.10/site-packages/django/forms/forms.py", line … -
How to send data from list to create?
I have a problem, I would like to transfer the appropriate field parameters from one list to the form for creating something else. The names of the fields match but they are not the same in both and I would like to send only those that are the same. Example - I have a list of requests and on this list I have a button next to each record. After press the button i would like to redirect to add customer form where I will have autofill data from list request. What can I do? def add_customer_from_list(request, pk): application = Contact.objects.get(id=pk) #data from Contact list form = CustomerForm(request.POST, instance=application)#to CustomerForm if form.is_valid(): name = form.cleaned_data['name'] #same email = form.cleaned_data['email'] #same phone_number = form.cleaned_data['phone_number']#same address = form.cleaned_data['address'] dog_name = form.cleaned_data['dog_name']#same dog_age = form.cleaned_data['dog_age'] service_type = form.cleaned_data['service_type']#same (multi choice) training_place = form.cleaned_data['training_place'] contact_date = form.cleaned_data['contact_date'] source = form.cleaned_data['source'] status = form.cleaned_data['status'] notes = form.cleaned_data['notes'] customer = Customer(name=name, email=email, phone_number=phone_number, address=address, dog_name=dog_name, dog_age=dog_age, service_type=service_type, training_place=training_place, contact_date=contact_date, source=source, status=status, notes=notes) customer.save() return redirect('xxx') return render(request, 'xxx', {'form': form}) I try do somethin in view and templates -
Add an endpoint for borrowing return
I have this tasks for borrowing books in the library: Implement return Borrowing functionality Make sure you cannot return borrowing twice Add 1 to book inventory on returning Add an endpoint for borrowing books POST: borrowings//return/ - set actual return date (inventory should be made += 1) I can not understand how to make a return endpoint. book/models.py from django.db import models class Book(models.Model): COVER_CHOICES = [("HARD", "Hard cover"), ("SOFT", "Soft cover")] title = models.CharField(max_length=255) authors = models.CharField(max_length=256) cover = models.CharField(max_length=15, choices=COVER_CHOICES) inventory = models.PositiveIntegerField() daily_fee = models.DecimalField(max_digits=7, decimal_places=2) class Meta: ordering = ["title"] def __str__(self): return ( f"'{self.title}' by {self.authors}, " f"cover: {self.cover}, " f"daily fee: {self.daily_fee}, " f"inventory: {self.inventory}" ) def reduce_inventory_book(self): self.inventory -= 1 self.save() def increase_inventory_book(self): self.inventory += 1 self.save() borrowing/models.py from django.conf import settings from django.contrib.auth.models import AbstractUser from django.core.exceptions import ValidationError from django.db import models from book.models import Book class Borrowing(models.Model): borrow_date = models.DateField(auto_now_add=True) expected_return_date = models.DateField() actual_return_date = models.DateField(null=True, blank=True) book = models.ForeignKey(Book, on_delete=models.PROTECT, related_name="borrowings") user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="borrowings" ) @staticmethod def validate_book_inventory(inventory: int, title: str, error_to_raise): if not (inventory > 0): raise error_to_raise( {"book": f"There is currently no book: {title} to borrow"} ) def clean(self): Borrowing.validate_book_inventory( self.book.inventory, self.book.title, ValidationError ) … -
Request Handling at backend (Django)
I have two api endpoints 1- stockpurchases/ || stockpurchases/{id}/ 2- stockpurchases/{id}/stocks/ || stockpurchases/{id}/stocks/{id}/ So if some one want to purchase he should create a stockpurchase first and than add a stock to it and when someone POST stock I plus quantity and amount of stockpurchase. The problem is if some one call POST request consecutively for a loop the amount operation will goes incorrect. I want handle multiple request at the backend. Supose if the server gets consecutive request to perform operation how can i make others request wait till completion of first procedsed. After that second request is processed and so on. StockPurchase Model class StockPurchase(models.Model): qty = models.IntegerField(default=0) amount = models.IntegerField(default=0) Stock Model class Stock(models.Model): stockpurchase = models.ForeignKey("StockPurchase", on_delete=models.CASCADE, related_name='stocks') product = models.ForeignKey("Product", on_delete=models.CASCADE, related_name='stocks') project = models.ForeignKey("Project", on_delete=models.CASCADE, related_name='stocks') rate = models.IntegerField() def save(self, *args, **kwargs): if not self.pk: self.stockpurchase.amount += self.rate self.stockpurchase.qty += 1 self.stockpurchase.save() super().save() So if I Call like this with await no issue async function create() { for (let i = 0; i < 10; i++) { let response = await fetch( "http://localhost:8000/api/stockpurchases/2/stocks/", { method: "POST", body: bodyContent, headers: headersList, } ); } } but if call it without await async function the … -
How to style the validation error list display by changing the error class by overwriting built-in form templates. error_class errorlist ErrorList
I couldn't find an up-to-date answer, so I'll write my own solution based on the Django documentation https://docs.djangoproject.com/en/4.2/ref/forms/api/#how-errors-are-displayed. Explain: I override built-it templates of ErrorList using TemplatesSetting() which refers to the template engine. Now I can change HTML in custom templates. `from django.forms.renderers import TemplatesSetting from django.forms.utils import ErrorList class CustomErrorList(ErrorList): def __init__(self, initlist=None, error_class=None, renderer=None): super().__init__(initlist, error_class="list-group", renderer=TemplatesSetting()) template_name = "forms/errors/default.html" template_name_text = "forms/text.txt" template_name_ul = "forms/errors/ul.html" class OfferForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.error_class = CustomErrorList class Meta: model = Offer exclude = ['city', 'user', 'is_active', 'count_of_views', 'in_favorites']` settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] in ul.html: {% if errors %}<ul class="list-group">{% for error in errors %}<li class="list-group-item text-white bg-danger">{{ error }}</li>{% endfor %}</ul>{% endif %} -
Unable to reset password in Django
I have an app which allows the user to reset password. I user the django authentification system but everytime I want to send an email I get the error ' 535, b'5.7.8 Username and Password not accepted. '. I have already generated and app password and replace the password in my "settings.py" but I still get this error. -
Sort objects in django admin panel based on a charfield which also have certain characters like $, Euro Symbol, comma, etc.,
In the Django Admin panel, I want a functionality for admin that allows him to Sort the car based on price. Here price is a CharField and contains different characters other than numbers in string format. which makes it difficult to sort. I want to filter the Cars based on price but price is a string and contains characters like $, comma and Euro symbols. I don't understand how to filter this. class MostExpensiveCars(admin.SimpleListFilter): title = _("Most Expensive Cars") parameter_name = "most_expensive_cars" def lookups(self, request, model_admin): return ( ("today", _("Today")), ("yesterday", _("Yesterday")), ("this_week", _("This Week")), ) def queryset(self, request, queryset): if self.value() == "today": # get today's date today = datetime.today().date() # get the most expensive cars sold today queryset = queryset.filter(sold_on=today) if self.value() == "yesterday": # get yesterday's date yesterday = datetime.today().date() - timedelta(days=1) queryset = queryset.filter(sold_on=yesterday) # get the most expensive cars sold yesterday # return queryset if self.value() == "this_week": # get the most expensive cars sold this week seven_days_ago = datetime.today().date() - timedelta(days=7) queryset = queryset.filter(sold_on__gte=seven_days_ago) # TODO: code to filter queryset by price since the price is a string # and contains many characters like $, commas, etc. ........... @admin.register(Car) class CarAdmin(admin.ModelAdmin): list_display = [ … -
Doesn't the parent model's object of "one to one relationship" have "_set" in Django?
I have Person and PersonDetail models below which have one-to-one relationship: class Person(models.Model): name = models.CharField(max_length=20) class PersonDetail(models.Model): person = models.OneToOneField(Person, on_delete=models.CASCADE) age = models.IntegerField() gender = models.CharField(max_length=20) But, when using persondetail_set of a Person object as shown below: obj = Person.objects.all()[0] print(obj.persondetail_set.all()) # ↑ ↑ Here ↑ ↑ There is the error below: AttributeError: 'Person' object has no attribute 'persondetail_set' So, I changed one-to-one relationship to one-to-many relationship as shown below: class PersonDetail(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) # ... Then, there was no error: <QuerySet [<PersonDetail: 32 Male>]> Or, I changed one-to-one relationship to many-to-many relationship as shown below: class PersonDetail(models.Model): person = models.ManyToManyField(Person) # ... Then, there was no error: <QuerySet []> So, doesn't the parent model's object of one-to-one relationship have _set in Django? obj = Person.objects.all()[0] print(obj.persondetail_set.all()) # ↑ ↑ Here ↑ ↑ -
Cannot render values in django template using for loop
So i have a zipped list inside my view and I have passed it into context like this: combined_data = zip(hostnames_list, values, values1, values2, values3, values4, values5) context = {'combined_data': combined_data} return render(request, 'base/snmp-table.html', context) but when i try to render this data into the django template like this, the data is not displayed: <table> <thead> <tr> <th>Hostname</th> <th>Value1</th> <th>Value2</th> <th>Value3</th> <th>Value4</th> <th>Value5</th> <th>Value6</th> </tr> </thead> <tbody> {% for host, val1, val2, val3, val4, val5, val6 in combined_data %} <tr> <td>{{host}}</td> <td>{{val1}}</td> <td>{{val2}}</td> <td>{{val3}}</td> <td>{{val4}}</td> <td>{{val5}}</td> <td>{{val6}}</td> </tr> {% endfor %} </tbody> </table> </table> <script type="text/javascript"> setTimeout(function () { location.reload(); }, 2 * 1000); </script> The lists which are zipped are not empty because when i do this inside my view: for host, val1, val2, val3, val4, val5, val6 in combined_data: print(host, val1, val2, val3, val4, val5, val6) I get the output in my console 10.1.1.1 not found not found not found not found not found not found 10.1.1.2 not found not found not found not found not found not found Note: 'not found' is the value inside list. Any insight please? thank you -
How to get an X from a range (1000, 0) in Django Template when you run through a for loop (0, 1000)?
Actually, I run through a regular loop: {% for post in posts %} And I need here X = 1000 then 999 then 998. {% endfor %} How to do it? Do you have any ideas? I tried: {% with x=1000 %} {% for post in posts %} {{ x|add:"-1" }} {% endfor %} {% endwith %} But it doesn't save that x. It shows 999 each time. -
How to serve two projects on same server one is django and another is django
I have created two projects one is python django and another is on Php as the backend. I want to connect its front end which is on flutter and put it on live .Suggests some ideas on how to do it. Please share some feasible ideas -
Add filtering parameters in drf_yasg Swagger in django-rest-framework Viewsets
I am using django-rest-framework Viewset and i have one list API in that i have to add filtering parameters start_date and end_date in request body in swagger. class SchoolManagementView(ViewSet): def __init__(self, *args, **kwargs): super().__init__(**kwargs) self.payload = {} self.college_list_service = CollegeListService(view=self) @swagger_auto_schema( operation_description="Listing Inward Document", responses={status.HTTP_200_OK: "Success"} ) def list(self, request, *args, **kwargs): self.payload = self.college_list_service.execute(request) return ResponseHandler.success(payload=self.payload) Note: Here i am using all my filter backends in "college_list_service" file -
Is it possible to feed data from a React POST request into a Django form without rendering that form on the frontend?
I am working on a basic login form for a hybrid React/Django web app. I would like to use the built in data-cleaning and validating methods of the Django LoginForm, but our frontend is pure React. Everything works as far as logging in, but I am feeding the raw body data into the authenticate function as shown here. def login_view(request): if request.method == "POST": form_data = json.loads(request.body.decode('utf-8')) user = authenticate(request, email=form_data["username"], password=form_data["password"]) if user == None: request.session["invalid_user"] = 1 logging.warning("Login form contains no user") login(request, user) My question is, is there any way to feed this form_data into the Django native LoginForm when I instantiate it? I would prefer to not recode all of the input validation that Django does already. I've tried instantiating a LoginForm like so: form = LoginForm(data=form_data) And then tried running form.full_clean(), but it doesn't seem to work. Any help would be greatly appreciated, thank you! -
Site downtime becuase of gunicron cpu utilization is 96%
We have djanog application that run with gunicorn. We eware facing site downtime because of high trafic. Gunicorn is utilizng 96 % of the cpu that what cauing the issue. Our system specification: 8 GB ram, 4 cpu How to setup gunicron in such way that it can handle more than 100 request per second ? What are the system specifcation required for handling 100 request per second ? Is gunicorn workers are cpu count ? -
model register but not creating table
on my django application I try to register model , python manage.py makemigrations , migrate works , but no database table found on admin.. `from django.contrib import admin.. << admin.py >> from .models import Product class ProductAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('product_name',)} list_display = ('product_name', 'price', 'stock', 'category', 'modified_date', 'is_available') admin.site.register(Product, ProductAdmin) ` -
Celery executing only one task at a time
I'm running celery on windows through this command celery -A project worker --concurrency=1 --loglevel=info -E -P gevent -Ofair but it only executes one task at a time, even tried to add some configurations import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") app = Celery("django_celery") app.conf.worker_prefetch_multiplier = 1 app.conf.task_acks_late = True app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() I've no idea what I'm doing wrong -
How Django process the post request sent from React? I have extracted the data from the POST request, but how show the data in a web browser?
I'm absolutely new to the field of frontend and backend. I sent a request from React to Django using "POST" and I have extracted data from the request I can print it in the terminal, but how to show the result in web browser from Django (i.e.8000/result/) it seems to use "GET" method but it fails because my data is extracted from POST request. So basicacly, I input a text and submitted to localhost:8000/result, so I want to show the result on this url or redirect to another and send it back to React. I don't know how to achieve this I used a pretty dumb method I save the data of request in tempory json and read the json in another function to render a browser through "GET". I tried to render or redirect to some url pages directly after process the "POST" request, but it apprently fails. views.py @api_view(["GET","POST"]) #class SubmitTextView(View): def post(request): if request.method =="POST": #print(True) text = request.body #print(type(text)) result = json.loads(text)["text"] json_data = json.dumps({"text":result}) #return HttpResponse(json_data, content_type='application/json') #return JsonResponse({"text":result}) #context = {'result':result,'headline':'Result Searched from Wikipedia'} #return render(request, 'my_template.html', context) with open("sample.json", "w") as outfile: outfile.write(json_data) return JsonResponse({"status":"success"}) def upload(request): with open('sample.json', 'r') as openfile: # … -
Django 'STATIC_ROOT' url giving PermissionError
I'm running collectstatic with docker-compose and nginx. When I run the command python manage.py collectstatic, I get a Permission denied error such as this: PermissionError: [Errno 13] Permission denied: '/project/static' I'm trying to link it also with nginx. Trying different combinations it doesn't seem to accept my static files and this error is popping out most of the times. I tried using changing ownership with chown but it tells me I'm not allowed to change ownership, and when adding sudo in before it says sudo: not found (I'm running the scripts through a .sh script file). This is django settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') And this nginx configuration: server { listen ${LISTEN_PORT}; location /static { alias /static/; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } Also changing the name of the folder in STATIC_ROOT didn't work. What am I doing wrong? -
editing a list in a different file
I am trying to edit a list in a different file in python django. I have a file called models.py and a file called details.py, details.py: DATA = [ {'height': '184', 'width': '49'} {'height': '161', 'width': '31'} {'height': '197', 'width': '25'} {'height': '123', 'width': '56'} {'height': '152', 'width': '24'} {'height': '177', 'width': '27'} ] def edit_list(h,w): for info in DATA: if info['height'] == h: info['width'] = w return True models.py: from abc.details import edit_list height = '161' new_width = '52' update_data = edit_list(height, new_width) #this doesn't work, when I check the file nothing changes in the list :/ What is the best approach to make this possible?? (I don't want to import this list to DB and just update the width there, I want the width to update inside the file itself, removing details.py file and creating a new one using python whenever an edit takes place is not possible because few other functions are taking data from the list as well all the time. -
Django, ReactJS & Babel: Integrating a React App with Django
I'm using Django 4 and wish to integrate a ReactJS application within the Django framework. I chose to use the exact approach here to start and installed it identically as outlined: https://dev.to/zachtylr21/how-to-serve-a-react-single-page-app-with-django-1a1l Here's a list of the installed components and versions: ├── @babel/core@7.20.12 ├── @babel/preset-env@7.20.2 ├── @babel/preset-react@7.18.6 ├── babel-loader@9.1.2 ├── clean-webpack-plugin@4.0.0 ├── css-loader@6.7.3 ├── react-dom@18.2.0 ├── react@18.2.0 ├── style-loader@3.3.1 ├── webpack-bundle-tracker@0.4.3 ├── webpack-cli@5.0.1 └── webpack@5.75.0 I do not want to post all of my code here since it is 100% identical to the code in the link above. Unfortunately, I'm receiving a strange error in the console: GET http://127.0.0.1:8001/frontend/static/frontend/frontend-dc3188e75be82e0a01e0.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:1 Refused to execute script from 'http://127.0.0.1:8001/frontend/static/frontend/frontend-dc3188e75be82e0a01e0.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. This appears to be related to the path, but the referenced JS filename is spelled correctly and exists at the exact referenced path. The server console also displays a similar error: Not Found: /frontend/static/frontend/frontend-dc3188e75be82e0a01e0.js If anyone has insight or experience here, please let me know. I'm at a loss and need to walk away...again. Thank you in advance! -
Inventory table and sales table - Python | django
I created an inventory table called Products. How do I make a sales table with the products in the inventory table and the products in the sales table replicate according to the quantity in the inventory table. And when I sell a product in the sales table, it decreases in the quantity of the stock table. -
How to Call Two Fields From One Model in Django View
I now have a model and I want to display two fields of it in the same view.Then display them in the details template. What is the best way to do that? my model: class Book(models.Model): class Meta : verbose_name_plural = 'Books' category = models.ForeignKey(Categorie,on_delete=models.CASCADE,null=True, related_name="apps") book_slug = models.SlugField(blank=True,allow_unicode=True,editable=True) book_title = models.CharField(max_length=50 , null=True) book_picture = models.ImageField(upload_to='imgs' , null=True) book_description = RichTextUploadingField(null=True,blank=True) book_size = models.CharField(max_length=20 , null=True) book_created_at = models.DateField(auto_now_add=True) book_updated_at = models.DateField(auto_now=True) book_auther = models.CharField(max_length=100 , null=True) my views: def book_details(requset ,book_slug): book = get_object_or_404 (Book, book_slug = book_slug) try : book = Book.objects.filter(book_slug = book_slug) except : raise Http404 similar_books = Book.objects.filter(book_auther = book_slug) ------ >>> Here is my query context ={ 'book' :book, 'similar_books':similar_books, } return render( requset,'book.html',context) my template: <div class="row"> {% for b in book %} <div> <img src="{{ b.book_picture.url }}" class="Rounded circle Image" height="150" width="150" alt=""> <a href="{{b.get_absolute_url}}">{{b.book_title}}</a> </div> {% endfor %} </div> <div class="row"> {% for sb in similar_books%} <div> <img src="{{ sb.book_picture.url }}" class="Rounded circle Image" height="150" width="150" alt=""> <a href="{{sb.get_absolute_url}}">{{sb.book_title}}</a> </div> {% endfor %} </div> -
Stock checker in python, test several objects simultaneously
Ultimately, my goal is to to know if one of my users submitted an existing Stock Symbol in my webapp's form. So, I have a string with several words. I want to identify an active finance symbol (EURUSD=X, AAPL, ...). Because the string will count no more than 10 words, I decided to test all word independently through a yfinance request. If the stock symbol exists, Yahoo API will send me data, otherwise there is an error message 'Unknown Stock symbol'. import yfinance as yfs string = str("23/01/2023 24/02/2021 hello Xlibidish sj monkey jhihi EURUSD=X") x = string.split() #API CALL Tickertest = yf.Ticker(x) ainfo = Tickertest.history(period='1y') print(len(ainfo)) Therefore, I need a function that: split all string's variable into words. Done. Test all words, one by one in the API Identify the API call that sends data (might be done with a length condition as the unknown symbols all have length < 40. -
Reverse for 'update-project' with arguments '('',)' not found. 1 pattern(s) tried: ['update\\-project/(?P<pk>[0-9]+)/\\Z']
Trying to create an update function for a Project Model in Django but i've run into a problem. Here's what i have so far update view function @login_required def updateProject(request, pk): project = Project.objects.get(id=pk) form = ProjectForm(instance=project) if request.method == 'POST': project.name = request.POST.get('name') project.description = request.POST.get('description') project.save() return redirect('project', pk=project.id) context = {'form': form, 'project': project} return render(request, 'projects/project_form.html', context) This is how I'm calling it in the template <li><a href="{% url 'update-project' project.id %}">Edit</a></li> and this is what the urlpattern is path('update-project/<int:pk>/', views.updateProject, name='update-project'), What am I missing?