Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Skip DRF Authentication on Graphql Query
I am trying to add my existing authentication on GraphQl api in my Django project. I have done the following: class DRFAuthenticatedGraphQLView(GraphQLView): @classmethod def as_view(cls, *args, **kwargs): view = super(DRFAuthenticatedGraphQLView, cls).as_view(*args, **kwargs) view = permission_classes((IsAuthenticated,))(view) view = authentication_classes((TokenAuthentication, ))(view) view = api_view(['POST','GET'])(view) return view urlpatterns = [ path('graphql', csrf_exempt(DRFAuthenticatedGraphQLView.as_view(graphiql=True))) ] This applies authentication checks on all mutations and queries of GraphQl. I want 1 query to be without an authentication check. How can I skip that Query? -
addEventListener doesn't see change in dropdown list
I'm learning django and javascript and i have a problem witch addEventListener function. It doesn't work. Any idea what I'm doing wrong? dropbox html: <div class="ui selection dropdown" id="okej"> <input type="hidden" name="artykuł"> <i class="dropdown icon"></i> <div class="default text" id="mozeto">Wybierz artykuł</div> <div class="menu" id="produktybox"> <!-- <div class="item" data-value="0">baton</div>--> <!-- <div class="item" data-value="1">konserwa</div>--> <!-- <div class="item" data-value="2">ziemniaki</div>--> <!-- <div class="item" data-value="3">pomidory</div>--> </div> </div> myjs.js const choose=document.getElementById("okej") - - - $.ajax({ type: 'GET', url: 'produktJson/', success : function(response) { console.log('success', response) const produktyData = response.produkty produktyData.map(item=>{ const option=document.createElement('div') option.textContent = item option.setAttribute('class','item') option.setAttribute('data-value', item.nazwa) produktyDataBox.appendChild(option) }) }, error: function (response) { console.log ('error', error)}, }) Here I'm looking for a problem. choose.addEventListener('change' , e=>{ console.log('success! I see it!') }) -
Querying objects with the same value and distinguishing them in python django
I'm having trouble querying objects that have the same value from the database, i normally use the .first() and .last() to distinguish between two queries with the same value. But the program that I'm making gives me more than two objects with the same value! What should I use in my case, it's been such a headache such that I tried using .second(). But I failed! Anyone knows anything? -
Urlpatterns: category/subcategory/article-slug
Django==3.2.5 re_path(r'^.*/.*/<slug:slug>/$', Single.as_view(), name="single"), Here I'm trying to organize the following pattern: category/subcategory/article-slug. Category and subcategory are not identifying anything in this case. Only slug is meaningful. Now I try: http://localhost:8000/progr/django/1/ And get this: Page not found (404) Request Method: GET Request URL: http://localhost:8000/progr/django/1/ Using the URLconf defined in articles_project.urls, Django tried these URL patterns, in this order: admin/ ^.*/.*/<slug:slug>/$ [name='single'] articles/ ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ The current path, progr/django/1/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Could you help me? -
how to create a trigger with Sqlite in django
I have a "quenstion" and "comments" model I wanted to automatically delete any questions that will not be commented after 30 days of its publication -
RemovedInDjango40Warning at /accounts/log-in/ when logging in
RemovedInDjango40Warning at /accounts/log-in/ django.utils.http.is_safe_url() is deprecated in favor of url_has_allowed_host_and_scheme(). Request Method: POST Request URL: http://127.0.0.1:8000/accounts/log-in/ Django Version: 3.2.5 Exception Type: RemovedInDjango40Warning Exception Value: django.utils.http.is_safe_url() is deprecated in favor of url_has_allowed_host_and_scheme(). Exception Location: C:\Users\keyvan\Desktop\Django_ECommerce\venv\lib\site-packages\django\utils\http.py, line 329, in is_safe_url Python Executable: C:\Users\keyvan\Desktop\Django_ECommerce\venv\Scripts\python.exe Python Version: 3.8.6 Python Path: ['C:\\Users\\keyvan\\Desktop\\Django_ECommerce', 'C:\\Users\\keyvan\\Desktop\\Django_ECommerce', 'C:\\Program Files\\JetBrains\\PyCharm ' '2021.1\\plugins\\python\\helpers\\pycharm_display', 'C:\\Program Files\\Python38\\python38.zip', 'C:\\Program Files\\Python38\\DLLs', 'C:\\Program Files\\Python38\\lib', 'C:\\Program Files\\Python38', 'C:\\Users\\keyvan\\Desktop\\Django_ECommerce\\venv', 'C:\\Users\\keyvan\\Desktop\\Django_ECommerce\\venv\\lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2021.1\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] -
Materialize sidenav not working on small devices
I am using Materialize with Django. Navbar is working fine on large screens, but sidenav is not working on small screens. var elems = document.querySelectorAll('.sidenav'); var sidenavInstance = M.Sidenav.init(elems); <a href="#" data-target="mobile-nav" class="sidenav-trigger "> <i class="material-icons">menu</i></a> <ul id="slide-out" class="sidenav"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Academics</a></li> <li><a href="#">Events</a></li> <li><a href="#">Contact</a></li> <li><a href="#">Login</a></li> </ul> This is my code snippet. I am getting the error "Cannot read property 'M_Sidenav' of null" on small screens. Could anybody tell me why am I getting this error? -
Accessing field values across multiple HTML pages with JavaScript
I am practicing Django on a dummy project and it contains several HTML pages. The pages have forms that have some numeric fields. I want to perform some calculation and logic to define some particular fields in one form by accessing fields from another form in another HTML page. I am suggested to use Local Storage to achieve that. But I'm having some difficulties there. Hope I can get some help here. Below are my templates or the HTML pages. package.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Package Form</title> </head> <body> <form action="" method="post" novalidate> <input type="hidden" name="csrfmiddlewaretoken" value="MmwcfNcoQmNheHv6HKNQXkD4ZzjuAMqu3UIejr9MSmnWom2hRXrTK5er9k2BBi8N"> <p><label for="id_package_form-date_of_admission">Date of admission:</label> <input type="text" name="package_form-date_of_admission" required id="id_package_form-date_of_admission"></p> <p><label for="id_package_form-max_fractions">Max fractions:</label> <input type="number" name="package_form-max_fractions" onfocus="mf();" onblur="tp();" required id="id_package_form-max_fractions"></p> <p><label for="id_package_form-total_package">Total package:</label> <input type="number" name="package_form-total_package" onfocus="tp();" onblur="onLoad();" step="0.01" required id="id_package_form-total_package"></p> <button type="submit" id="savebtn">Save</button> </form> <script src="/static/account/js/myjs.js"></script> <script src="/static/account/js/test.js"></script> </body> </html> Note: The total_package field itself is derived after performing logical calculations on some other fields, which you will see in the myjs.js codes. receivables.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Receivables</title> </head> <body onload="onLoad();"> <form action="" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="Ft1uZYJAKpGvw9tgCt8vZbdospwZ5XHKW1dw3CGYMpgaGO0rMGMyMWOLCaf66tp3"> <p><label for="id_discount">Discount:</label> <input type="number" … -
run wordpress and django application on same Apache server | remove Port number from django web url
I am running wordpress site on servver and I installed django application on same linode server. I am able to run my django website/application on http://ip:8000 & http://domain-name:8000. I need information on where to edit setting to remove 8000 from django application in apache. installed ssl but domain-name giving 403 forbidded error on port 443. <VirtualHost *:80> ServerAdmin webmaster@localhost ServerAlias test.factory2homes.com DocumentRoot /home/ubuntu/env/mysite ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/env/mysite/ecom/static <Directory /home/ubuntu/env/mysite/ecom/static> Require all granted </Directory> Alias /media /home/ubuntu/env/mysite/ecom/media <Directory /home/ubuntu/env/mysite/ecom/media> Require all granted </Directory> <Directory /home/ubuntu/env/mysite/ecom> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/ubuntu/env/mysite/mysite/wsgi.py WSGIDaemonProcess django_app python-path=/home/ubuntu/env/mysite python-home=/home/ubuntu/env WSGIProcessGroup django_app RewriteEngine on RewriteCond %{SERVER_NAME} =test.factory2homes.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet -
Allowing users in Django app to use same form to create two objects
I am trying to create a simple, Django-based To-do web app. Each task in the app will be linked to tags. I can achieve the above by creating models for both the tasks and the tags with many:many relationship. When I create the form for user to create new tasks (using ModelForm), they are also offered up a a way to multi-select tags. All of the above is fine. However, I am trying to figure out a way to give the user the ability to ‘create’ new tags when they’re creating new tasks as well. Ability for user to enter comma separated tags that get added to db as individual ‘tag’ objects. Can this also be done while retaining the choice for users to select from existing tags? How do I achieve any or all of this? Any help would be much appreciated. Thanks! -
Django: Which is the most efficient way to record likes/dislikes for contents like blogs or images in a medium to high traffic website?
I am quite new to web development, but based on my initial research I found that it is not efficient to write to database every now and then. For like function, suppose many people are liking a content, it needs to write to the database every time and it feels not right. What is the best way to tackle such a problem? Is it possible to record all the likes in a cache and then write to db at once at specific intervals? or are there better methods? How does big companies do it? Can someone post some leads or help with directions on how to proceed? Thanks in advance. -
The Django form could not be submitted accordingly
views.py @login_required(login_url='login/') def add_country(request): if request.method == 'POST': form = CountryForm(request.POST,request.FILES) if form.is_valid(): new_form = form.save(commit=False) new_form.edited_by = request.user new_form.save() return redirect('country_details') else: form = CountryForm() context = {'form':form} return render(request,'add_country.html',context) models.py class Countries(models.Model): CONTINENTS = [ ('Asia','Asia'), ('Europe','Europe'), ('Africa','Africa'), ('Oceania','Oceania'), ('North America','North America'), ('South America','South America'), ] name = models.CharField(max_length=75) continent = models.CharField(max_length=50,choices=CONTINENTS,null=True) landmark = models.CharField(max_length=100,null=True) food = models.CharField(max_length=100,null=True) entertainment = models.CharField(max_length=100,null=True) flag = models.FileField(upload_to='flags', default='default.png',null=True) image = models.FileField(upload_to='travel', default='default.png',null=True) edited_by = models.OneToOneField(User,on_delete=models.CASCADE,null=True) last_updated = models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.name add_country.html <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form.name.label }}<br> {{ form.name }}<br><br> {{ form.landmark.label }}<br> {{ form.landmark }}<br><br> {{ form.food.label }}<br> {{ form.food }}<br><br> {{ form.entertainment.label }}<br> {{ form.entertainment }}<br><br> {{ form.flag.label }}<br> {{ form.flag }}<br><br> {{ form.image.label }}<br> {{ form.image }}<br><br> <input type="submit" class="btn btn-primary" value="Add"> </form> I have an issue that after I added the edited_by to assign the currently logged in user into that column then the form could not be submitted and only stayed on the same page instead of redirecting to the page that I want. I have tried different ways to make the form being submitted such as put request.method == "POST" and the page didn't work. However before I added … -
Is it possible to have a foreign key referring to several classes in Django?
I am modelling an accounting system. I have the following models: class GeneralAccount(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') name = models.CharField(max_length=100, verbose_name='Account Name') code = models.CharField(max_length=10, verbose_name='Account Code') balance = models.DecimalField(max_digits=9, decimal_places=2) class InventoryAccount(GeneralAccount): description = models.TextField() price = models.DecimalField(max_digits=9, decimal_places=2) cost = models.DecimalField(max_digits=9, decimal_places=2) available_stock = models.DecimalField(max_digits=9, decimal_places=2) value = models.DecimalField(max_digits=9, decimal_places=2) class JournalEntry(models.Model): transaction_date = models.DateField(verbose_name='Transaction Date', default=django.utils.timezone.now) account_from = models.ForeignKey(GeneralAccount, on_delete=models.PROTECT) # THIS IS THE PROBLEM account_to = models.ForeignKey(GeneralAccount, on_delete=models.PROTECT) # THIS IS THE PROBLEM amount = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True) My problem is in the account_from/account_to fields. Currently, it is only accepting a GeneralAccount but I also want it to accept an InventoryAccount because essentially it is an MPTTModel/GeneralAccount with just some specialized fields. The only thing I can think of is to create a separate JournalEntry class for Inventory but I would prefer just to streamline it. Actually, if I could have only one MPTT model (i.e One Account Model) that would be preferrable. Is there way around this? P.S. I have checked several accounting github repos but essentially they are not implementing a subsidiary ledger accounts. They are all general ledger accounts. The separate InventoryAccount class is my attempt to implement a … -
Should I make a separate django project for crawling/scraping part?
I recently made an online-post-curating service with django. I now upload posts manually everyday but finally realized web-crawler/scraper is highly needed to save my time. In this case, is it better to make a separate django project(for the crawler only)? Or just starting a new app in the existing project is enough? [Advantage/Ground of making separate project for crawler (I guess)] Totally different dependencies needed, so new project Mainly asynchronous tasks unlike the existing service The function is very universal (not really related to post-curating service) Server spec. for crawler must be different, so be prepared in advance with separate project. [Opposite side - making an app is inough] For asynchronous tasks, just adding some library like Celery in your project is enough Running multiple projects demands lots and lots of additional effort Two projects using one database(saving and reading posts) at the same time can be a threat in some day Sorry for the tacky question and thank you in advance! -
django __in queryset with very large list is too slow
I have this filter in views: cat_ids = list(models.Catalogue.objects.only('city', 'district').filter( Q(*[Q(city__contains=x) for x in city_district], _connector=Q.OR) | Q(*[Q(district__contains=x) for x in city_district], _connector=Q.OR) ).values_list('pk', flat=True)) result = models.Catalogue.objects.filter(pk__in=cat_ids) cat_ids is a very large list (over 10000 data). django return result in 5 seconds. How can I improve this query? Is there any alternative for this? -
Value Error: Cannot query "post": Must be "UserProfile" instance
I am getting the Value Error: Cannot query "post": Must be "UserProfile" instance when I make a get request to call PostListView.as_view(). Here is my model.py : from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length=30) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() password = models.CharField(max_length=100) def __str__(self): return self.user.username class Post(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) title = models.CharField(max_length=100) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title views.py : class PostListView(ListAPIView): serializer_class = PostSerializer permission_classes = [AllowAny] def get_queryset(self): """Returns only the object related to current user""" user = self.request.user return Post.objects.filter(user=user) Also, I want a Foreign key relationship exists between User and Post on Model-level, not on the Database level. -
Save .xlsx file to Azure blob storage
I have a Django application and form which accepts from a user an Excel(.xlsx) and CSV (.csv) file. I need to save both files to Azure Blob Storage. I found it to be trivial to handle the .csv file with the following code: from azure.storage.blob import BlobServiceClient blob_service_client = BlobServiceClient.from_connection_string(os.getenv('STORAGE_CONN_STRING')) blob_client = blob_service_client.get_blob_client(container="my-container-name", blob=form.cleaned_data.get('name_of_form_field_for_csv_file')) blob_client.upload_blob(form.cleaned_data.get('name_of_form_field_for_csv_file'')) However, I've been unable to figure out how to save the .xlsx file. I--perhaps somewhat naively--assumed I could pass the .xlsx file as-is (like the .csv example above) but I get the error: ClientAuthenticationError at /mypage/create/ Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. I found this SO Answer about the above error, but there's no concensus at all on what the error means and I've been unable to progress much further from that link. However, there was some discussion about sending the data to Azure blob storage as a byte stream. Is this a possible way forward? I have also learned that .xlsx files are compressed so do I need to first decompress the file and then send it as a byte stream? If so, has anyone got any experience with this who … -
Why do I get TCP/IP error when trying to create DB in my Lambda?
So I'm trying to deploy my Django project using lambda, with zappa. I'm using MySQL for DB engine. Now after doing some research, I realized that I needed to create a custom Django command to create DB, since I'm using MySQL. So I created crate_db command, zappa updated, then ran zappa manage dev create_db. Then I got this error: 2004 (HY000): Can't create TCP/IP socket (97) below is my create_db.py file, for your information. import sys import logging import mysql.connector import os from django.core.management.base import BaseCommand, CommandError from django.conf import settings rds_host = os.environ.get("MY HOST") db_name = os.environ.get("") user_name = os.environ.get("MY USERNAME") password = os.environ.get("MY PASSWORD") port = os.environ.get("3306") logger = logging.getLogger() logger.setLevel(logging.INFO) class Command(BaseCommand): help = 'Creates the initial database' def handle(self, *args, **options): print('Starting db creation') try: db = mysql.connector.connect(host=rds_host, user=user_name, password=password, db="mysql", connect_timeout=10) c = db.cursor() print("connected to db server") c.execute("""CREATE DATABASE bookcake_db;""") c.execute("""GRANT ALL ON bookcake_db.* TO 'ryan'@'%'""") c.close() print("closed db connection") except mysql.connector.Error as err: logger.error("Something went wrong: {}".format(err)) sys.exit() Any ideas? Thanks. -
How to populate OneToOne field from template side in django?
I am working on a small django-python project which has two models "staff_type" and "staff". In the staff_type model, only designation and date fields are populated. And in the staff model, there is OneToOneField relation of staff_type. Means whenever a user want to add staff first he/she will have to add staff_type and then in the staff module, user will choose the staff type (designation) from a select menu in which all the staff_type are shown respectively. Now, whenever a user select any designation (staff_type) and fill the entire form, I want to store the selected staff_type id in the staff model/table. Note: I have tried this from django admin, and it works perfectly but I want to do the same work in my own designed templates. Modles.py class staff_type(models.Model): designation = models.CharField(max_length=50) salary = models.IntegerField() datetime = models.DateTimeField() entrydatetime = models.DateTimeField( auto_now=False, auto_now_add=False) class staff(models.Model): staff_type = models.OneToOneField(staff_type, on_delete=models.CASCADE) firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) fathername = models.CharField(max_length=50) city = models.CharField(max_length=50) country = models.CharField(max_length=50) state = models.CharField(max_length=50) zip = models.IntegerField(blank=True) address = models.CharField(max_length=100) contact =models.CharField(max_length=20) cnic = models.CharField(max_length=14) photo = models.ImageField() cv = models.ImageField() otherfiles = models.ImageField() views.py def add_staff_type(request): if request.method == 'POST': designation = request.POST.get('designation') salary = … -
How to connect this two check box
how to connect input and output column.When one box is checked in input column,the other check box with same name in output column should disable , both are iterated through for loop(django) -
I am getting the error : django.db.utils.IntegrityError: NOT NULL constraint failed: store_customer.email
Can anyone please help me solve this error? When I check out as a logged-in user and press the make payment button it clears the cart and does everything that it is supposed to. The problem is when I do the same for a guest user it does not clear the cart or register anything in the database. The payment button does nothing. error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\django\ecommerce\ecomm\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\django\ecommerce\ecomm\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\django\ecommerce\ecommerce\store\views.py", line 73, in processOrder customer, order = guestOrder(request, data) File "D:\django\ecommerce\ecommerce\store\utils.py", line 66, in guestOrder customer, created = Customer.objects.get_or_create( File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\query.py", line 588, in get_or_create return self.create(**params), True File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\query.py", line 453, in create obj.save(force_insert=True, using=self.db) File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\base.py", line 763, in save_base updated = self._save_table( File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\base.py", line 906, in _do_insert return manager._insert( File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\query.py", line 1270, … -
HOW TO CREATE FILTERED DROPDOWN IN DJANGO INLINE ADMIN FORM
I am seeking to add a dropdown to an inline form in DJANGO based on the user selection. I require a PYTHONIC solution no jquery or javascript please. I have read two approaches. The first being to create a second form and override the default formset and altering the init function. The second approach to make use of the formfield_for_foreignkey option on the inline. Neither work because I can't get the context data of the form. The use-case is that I need to grab a field on the form. I then wish to use that variable to a related model variable. In have uploaded a screen-shot here of the OrderItem admin form. I wish to grab the "PRODUCT" line on the orderitem. Using that instance of the PRODUCT I then want to access the "packaging" variable of that product instance. The issue I run into is that neither option described above provides easy access to the form values. Code is below: RELEVANT MODELS class OrderItem(models.Model): rx_written = models.DateField(default=datetime.date.today) order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) doctor = models.ForeignKey(Practitioner, on_delete=models.CASCADE, blank=True, null=True) pet = models.ForeignKey(Pet, on_delete=models.CASCADE, blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) tax = models.DecimalField(max_digits=10, decimal_places=2, … -
how to send image file from requests after getting it from post api
i am creating post writing project. when user upload image it send that image to django with POST request and after that i want to send that image to IMGUR from same post django api with my access_token because i want to key my credentials private. because i dont want to store image to my django server. but i cant send image to IMGUR directly because of accss token. #My javascript code, django post request var myHeaders = new Headers(); myHeaders.append("Authorization", "Bearer mytokennnnnnnnnnnnnnnnnnnnnn"); var formdata = new FormData(); formdata.append("upload", fileInput.files[0], "/C:/mypc/myname/Downloads/unsplash.png"); var requestOptions = { method: 'POST', headers: myHeaders, body: formdata, redirect: 'follow' }; fetch("http://127.0.0.1:8000/api/image/upload/", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); #my django api code class ImageUploadView(APIView): permission_classes = [ AllowAny ] parser_classes = [MultiPartParser, FormParser] def post(self, request): url = "https://api.imgur.com/3/upload" payload={} headers = {'Authorization': 'Bearer mytokennnnnnnnnnnnnnnnnnnnnnnn'} files=request.data['upload'] response = requests.request("POST", url, headers=headers, data=payload, files=files) print(response.text) return Response({"data":response.text}) my error for (k, v) in files: ValueError: too many values to unpack (expected 2) help me, how can i implement this logic -
Why do I get 502 error when deploying with Zappa? [closed]
So I'm trying to deploy my Django project with Zappa. I've done zappa install and zappa init, and now tried zappa deploy. Everything works fine, except the following error : Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code.. I've done some research and was advised to try zappa tail to see the log. However, all I see is [DEBUG] and can't find any [ERROR]s. What do you think is the problem? Thanks in advance. -
django filtering optimization
I have a large database and want to filter it based on some optional values from user. This is the listview class all_ads(generic.ListView): paginate_by = 12 template_name = 'new_list_view_grid-card.html' def get_queryset(self): usage = self.request.GET.get('usage') status = self.request.GET.get('status') last2week = datetime.datetime.now() - datetime.timedelta(days=14) last2week_q = Q(datetime__gte=last2week) status = status.split(',') if usage: usage = usage.split(',') else: usage = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'] intersections = list(set(status).intersection(usage)) result = models.Catalogue.objects.defer( "ads_json_html", "description" ).filter(last2week_q).order_by('-datetime') cat_ids = result.only('city', 'district').filter( Q(*[Q(city__contains=x) for x in city_district], _connector=Q.OR) | Q(*[Q(district__contains=x) for x in city_district], _connector=Q.OR) ).values_list('pk', flat=True) result = result.filter(pk__in=cat_ids) typ_ids = result.only('type').filter(type__in=intersections).values_list('pk', flat=True) result = result.filter(pk__in=typ_ids) return result models.py: class Source(models.Model): name = models.CharField(max_length=100, unique=False) def __str__(self): return self.name class Type(models.Model): name = models.CharField(max_length=100, db_index=True) def __str__(self): return self.name class Catalogue(models.Model): source = models.ForeignKey(Source, db_index=True, null=False, on_delete=models.CASCADE) city = models.CharField(db_index=True,max_length=100, null=True) district = models.CharField(db_index=True,max_length=100, null=True) type = models.ManyToManyField(Type, db_index=True) datetime = models.CharField(db_index=True, max_length=100, null=True) description = models.TextField(null=True) ads_json_html = models.TextField(null=True) def __str__(self): return self.source_token There are some other fields in Catalogue. The problem is filtering work fast on small database, but it is slow on large database. If I return result after last2week_q filter, it takes just 800 ms to filter and render template; But with cat_ids and typ_ids filtering, it …