Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I cannot get the page to render for the Django Apps tutorial
I am using the django tutorial to create my first polls app and to learn Django https://docs.djangoproject.com/en/5.0/intro/tutorial01/ Here are the files I have created so far: my app's file structure in mysite/urls.py I have this: from django.contrib import admin from django.urls import include, path urlpatterns = [ path("polls/", include("polls.urls")), path("admin/", admin.site.urls), ] In polls/urls.py I have this: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] And in polls/views.py I have the following: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") I have been trying with http://localhost:8000/polls/ and it still doesn't work! Any thoughts please on why that might be? booo! I have debugged in every way I can but everything looks correct to me. I am using GitHub's IDE but I don't think that should be the problem. -
How does `CachedReferenceField` from mongoengine work?
I'm working on a project in which I should use Django, grpc and mongodb. The db operations are readonly except when user interacts with the system for example posting comments or like a post, in that case I need to update the existing db document. I also want to store caches and I do it on retrieve() and list(). Now I have problem with updating caches when user comments for example, I am able to update caches which are made in retrieve() and list() both, but doing it also for nested documents is really hard (it's doable but is not a clean way), hence I want to know if CachedReferenceField comes handy for this purpose or not?? I mean I have my own caching method which is exteremly personal (which I don't like and wish to do it in a "cleaner" way, any help about it would be appreciated too;), doesn't this CachedReferenceField interupt my caching method? or it is internall and has nothing to do with my method of caching? I read the document but it's not so descriptive. -
Problem finding the image path in Django in one of the apps
I have 2 apps in my django project: -accounts & -ticketsales my project show images for ticketsales's model but dosen't show images for accounts's model, when I run my project, ProfileImages folder create out of media folder(that contain project's image) project's setting.py is: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,"static/") MEDIA_URL = "/media/" MEDIA_PATH = os.path.join(BASE_DIR,"media/") my image field in accounts model.py is(dosen't show this image): ProfileImage=models.ImageField(upload_to="profileImagess",null=True) profile view: @login_required def profileView(request): profile=request.user.profile context={ "profile":profile } return render(request,"accounts/profile.html",context) The image field in ticketsales model.py(show this image): Poster=models.ImageField(upload_to="concertImage",null=True I want to show my images in project but this dosen't happen -
Not submitting images in a form in django
It is even more accurate to say that the image name is sent, but nothing changes. I have a user model. The user has his own avatar (ImageField). I have written a form and put everything in the template. When submitting the form, everything is saved except the image. But when changing in the admin everything is fine. Why? Help me please already tried everything does not help!!!! settings.py: `MEDIA_ROOT = BASE_DIR / "media"` models.py: class Women(models.Model): class Status(models.IntegerChoices): DRAFT = 0, 'Черновик' PUBLISHED = 1, 'Опубликовано' title = models.CharField(max_length=255, verbose_name="Заголовок") slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="Slug", validators=[ MinLengthValidator(5, message="Минимум 5 символов"), MaxLengthValidator(100, message="Максимум 100 символов"), ]) photo = models.ImageField(upload_to="photos",default=None,blank=True,null=True,verbose_name="Фото") content = models.TextField(blank=True, verbose_name="Текст статьи") time_create = models.DateTimeField(auto_now_add=True, verbose_name="Время создания") time_update = models.DateTimeField(auto_now=True, verbose_name="Время изменения") is_published = models.BooleanField(choices=tuple(map(lambda x: (bool(x[0]), x[1]), Status.choices)), default=Status.DRAFT, verbose_name="Статус") cat = models.ForeignKey('Category', on_delete=models.PROTECT, related_name='posts', verbose_name="Категории") tags = models.ManyToManyField('TagPost', blank=True, related_name='tags', verbose_name="Теги") husband = models.OneToOneField('Husband', on_delete=models.SET_NULL, null=True, blank=True, related_name='wuman', verbose_name="Муж") objects = models.Manager() published = PublishedManager() def __str__(self): return self.title class Meta: verbose_name = "Известные женщины" verbose_name_plural = "Известные женщины" ordering = ['-time_create'] indexes = [ models.Index(fields=['-time_create']) ] def get_absolute_url(self): forms.py: class AddPostForm(forms.ModelForm): cat = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label="Категория не выбрана", label="Категории") husband = forms.ModelChoiceField(queryset=Husband.objects.all(), empty_label="Не замужем", required=False, … -
Django RestFrameWork.Serializers: ValueError: Cannot assign "OrderedDict()
How to solve this errorm tried almost everything. Have tried these solutions 1st from stackoverflow and 2nd from official website of DRF they did not work. class AddressCreateSerializer(ModelSerializer): class Meta: model = Address fields = '__all__' class BaseUserCreateSerializer(UserCreateSerializer): address = AddressCreateSerializer() class Meta(UserSerializer.Meta): model = BaseUser fields = ( 'inn', 'email', 'first_name', 'last_name', 'middle_name', 'date_of_birth', 'gender', 'phone_number', 'address' ) def create(self, validated_data): address_data = validated_data.pop('address') address_instance = Address.objects.create(**address_data) base_user_instance = BaseUser.objects.create(**validated_data, address=address_instance) return base_user_instance Error message: ValueError: Cannot assign "OrderedDict([('country', 'United States'), ('oblast', 'California'), ('city_village', 'Los Angeles'), ('street', 'Main Street'), ('house', '123'), ('apartment', 'Apt 456'), ('postal_code', '90001')])": "BaseUser.address" must be a "Address" instance. -
IDE cannot install Csv/Config/Decouple import
The problem is that the built-in debugger complains about these lines. from decouple import config, Csv from unipath import Path I tried to install via the IDE, as recommended by the debugger itself, but I get errors. Collecting decouple Using cached decouple-0.0.7.tar.gz (3.3 kB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' ERROR: Exception: Traceback (most recent call last): File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\cli\base_command.py", line 180, in exc_logging_wrapper status = run_func(*args) ^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\cli\req_command.py", line 245, in wrapper return func(self, options, args) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\commands\install.py", line 377, in run requirement_set = resolver.resolve( ^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 95, in resolve result = self._result = resolver.resolve( ^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 546, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 397, in resolve self._add_to_criteria(self.state.criteria, r, parent=None) File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 173, in _add_to_criteria if not criterion.candidates: ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_vendor\resolvelib\structs.py", line 156, in __bool__ return bool(self._sequence) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 155, in __bool__ return any(self) ^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 143, in <genexpr> return (c for c in iterator if id(c) not in self._incompatible_ids) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 47, in _iter_built candidate = func() ^^^^^^ File "C:\Users\OtterAndFinek\.virtualenvs\TattooFoundlerProject-1CIClaAs\Lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 182, … -
Django model ManyToManyField.add is not working
I have a model named TopicRoom and it has a field called creator which is a foreign key to the user model. And a many to many field called members which is a many to many rel to the user model @receiver(post_save, sender=models.TopicRoom) def add_topic_room_creator_as_a_member(instance, created, **kwargs): if created: print("added creator", instance.creator, instance) instance.members.add(instance.creator) print(instance.members.all()) When I create a new instance in the admin panel it prints this added creator bob@gmail.com TopicRoom object (24) <QuerySet [<User: bob@gmail.com>]> but when I view the model in the admin panel it shows that there are no members. And when I retrieve the model from the django manage.py shell, that also shows that there are no members for that object instance >>> TopicRoom.objects.get(id=24).members.all() <QuerySet []> -
How to correctly display static files in Django when debug = False?
what should I do if I used a command python manage.py collectstatic and don’t understand what needs to be done in order for static files to be located and displayed, i get only 404 when i try to load server and my css also dont working my settings.py: DEBUG = False ALLOWED_HOSTS = ['127.0.0.1'] PATH_TO_YOUR_STATIC_FOLDER= 'man/static/' STATICFILES_DIRS = [ BASE_DIR / "man/static", PATH_TO_YOUR_STATIC_FOLDER, ] STATIC_ROOT = BASE_DIR / "staticfiles" # Internationalization # https://docs.djangoproject.com/en/5.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' my files structure maybe i need to edit STATICFILES_DIRS? i was trying to change STATICFILES_DIRS in settings, but nothing -
Django access MultilinestringM in Postgis with Geometry(dim=3)
I do have Railway-lines using "Linear Referencing" stored as MultilinestringM in a Postgis-DB (created by FME). So each line has a certain code and along that line assets are placed (km_from, km_to). I do need read access only in order to calculate Linestring from the given from-to values. I try to access that Postgis Information with Django (Geodjango). Does anybody have a clue how to do so? Since in found out Django-Models do not support M-values i thought i try MulitlinestringField with dim=3 and use the z-Dimension which actually would be the m-Dimension. When accessing the DB I only get 2-dimensional Multilinestring even when setting dim=3. geom = models.MultiLineStringField( dim=3, srid=EPSG_CODE, blank=True, null=True, spatial_index=True ) # EPSG:3128=AustriaLambert Does anybody know how I can read in all 3 values from the MultilineStringM stored in Postgis? Many thanks Since in found out Django-Models do not support M-values i thought i try MulitlinestringField with dim=3 and use the z-Dimension which actually would be the m-Dimension. When accessing the DB I only get 2-dimensional Multilinestring even when setting dim=3. -
Difficulty using multiple filters simultaneously in Django view with HTMX
I'm encountering an issue with using multiple filters simultaneously in a Django view while incorporating HTMX for asynchronous updates. Here's a breakdown of the relevant code and the problem I'm facing: Html Requests: <input id="searchInput" class="form-control mb-4" type="search" name="searchInput" placeholder="Procure produtos pelo nome..." hx-get="{% url 'filter_products' %}?searchInput={{ searchInput.value }}" hx-trigger="input changed delay:500ms, search" hx-target="#search-results"> <select name="name_category" class="form-select px-0 py-0" multiple aria-label="multiple select example" hx-get="{% url 'filter_products' %}" hx-trigger="change" hx-target="#search-results"> Filter View: def filter_products(request): category_names = request.GET.getlist('name_category', []) search_query = request.GET.get('searchInput') print(search_query) print(category_names) # Start with all products products = Products.objects.all() # Apply category filter if any category is selected if category_names: category_filters = Q() for category_name in category_names: category_filters |= Q(categoryproducts__category__name_category=category_name) products = products.filter(category_filters) # Apply search filter if a search query is provided if search_query: products = products.filter(title__icontains=search_query) # Render the response using the products found html = render_to_string('products/products_list_partial.html', {'products': products}) return HttpResponse(html) The issue arises when I attempt to use both filters simultaneously. If I select a category while a search query is applied (or vice versa), the other filter gets cleared. For instance, if I have a search query applied and then select a category, the search query disappears, and only the category filter is applied. How … -
django.db.utils.ProgrammingError: column app_table.field does not exist
I have a django app which is already in production. I added some new tables and new fields to existing tables and all went well in the feature branch, but when I merged it with the main branch then i got the following error: django.db.utils.ProgrammingError: column appname_table.field does not exist. I have tried deleting migrations, running fake migrations and a lot of other stuff but it doesn't work out. It might be possible to delete database on local but not in production because already there is user data. -
Django dynamic pages. Why is my code not working?
I am creating a website for the sale of goods, and for each product I create a card based on data from the database. When a new card appears, a dynamic page based on the same database data should be automatically connected to it. The page is created, but the data from the model is not loaded. I watched the Django guide, and it showed this method using DetailView, from where I took the code. Please help me, I don't understand what the problem is. My code: views.py: class car(DetailView): model = inventory template_name = 'main/cars.html' context_object_name = 'inventory' urls.py: urlpatterns = [ path('inventory/<int:pk>', views.car.as_view(), name='cars'), ] cats.html: {% extends 'main/layout.html' %} {% block main %} {% for el in invent %} <div class="main-card "> <img src = '{{ el.img_1 }}' style=""> <h3 style="">{{ el.name }}</h3> <h4 style="">{{ el.rent }}</h4> <button><a href="{% url 'cars' el.id %}">Details</a></button> </div> {% endfor %} {% endblock %} models.py: class inventory(models.Model): name = models.CharField('Name', max_length=100) type = models.CharField('Type of car', max_length=6) img_1 = models.ImageField(upload_to='./sql_imgs') img_2 = models.ImageField(upload_to='./sql_imgs') img_3 = models.ImageField(upload_to='./sql_imgs') img_4 = models.ImageField(upload_to='./sql_imgs') img_5 = models.ImageField(upload_to='./sql_imgs') img_6 = models.ImageField(upload_to='./sql_imgs') img_7 = models.ImageField(upload_to='./sql_imgs') img_8 = models.ImageField(upload_to='./sql_imgs') MSRP = models.CharField('msrp', max_length=40) Purchase = models.CharField('purchase', max_length=40) rent = … -
inside inner class, parameter is not accessed despite being defined inside the class [closed]
I am trying to use an inner class inside an outer class, to make it easier to deal with a large number of parameters. I am currently using Django Rest API. Here is how it looks like now : `class MeasureProcessingContext: def __init__(self, request, cache_metadata, measure_ids, user, paging_id, result,to_include): self.request = request self.cache_metadata = cache_metadata self.measure_ids = measure_ids self.user = user self.size_in_query = 'size' in self.request.query_params self.eval_in_query ='eval' in self.request.query_paramsy self.measure_in_query = 'measure' in self.request.query_params self.page_in_query = 'page' in self.request.query_params self.paging_id = int(self.page_in_query) if self.page_in_query else 0 if self.eval_in_query else -1 self.result = result self.to_include = to_include` The issue is that I get an error as part of the argument, namely paging_id, even though it is being set, I get "paging_id" is not accessedPylance.Even though it is clearly being set as part of the init call. I was expecting to be able to sovle the "paging_id" is not accessedPylance error, such that even argument of the __init___function are defined. I have also tried without using a specific class (in this case MeasureProcessingContext) but due to the number of parameters, this solution ended up being not optimal. -
A Big Issue in django LoginView
there is an issue in Django with the LogoutView. when I try to enter the link 'accounts/logout' django server pops in the cmd: Method Not Allowed (GET): /accounts/logout/ Method Not Allowed: /accounts/logout/ [24/Feb/2024 13:48:11] "GET /accounts/logout/ HTTP/1.1" 405 0 this is the view file content: from django.urls import path, include from django.contrib.auth import views as auth_views from .views import showProfile, logout_user app_name = 'user' urlpatterns = [ path('logout/', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'), path('', include('django.contrib.auth.urls')), ] and this is the 'registration/logged_out.html' file content: {% extends "generic_base.html" %} {% block content %} <form method="post" action="{% url 'user:logout' %}"> {% csrf_token %} <button type="submit">Logout</button> </form> {% endblock content %} the templates file is located in the application 'accounts'. and the app_name = 'user' and this is the generic_base.html template content: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% block title %} <title>Donations</title> {% endblock title %} </head> <body> {% block content %} {% endblock content %} </body> </html> I tried a lot of ways to fix this issue, but none of them worked. I also saw all the provided solutions in Stack Overflow about this problem, but none of them worked. I also tried the solutions in Django built in Logout … -
serving static files in django on pythonanywhere
hello guys i need your help, i followed all the steps to serve my static files for my django application, i ran the collectstatic command, and i can see my files in the static folder in the root directory but i cant access them idk why for example i type https://scheduling.pythonanywhere.com/static/assets/css/style.css i get Not Found The requested resource was not found on this server., eventhough ik that my files are there (venv) 12:25 ~/Scheduling (main)$ ls Mappord appOrd manage.py mydb.sqlite3 requirements.txt static vercel.json -
Can messages sent through django channels be saved
I just created a chat app with Django channels and Daphne server but anytime I refresh a page, all the messages sent on that page disappear. I cant keep the messages after chats I created a model to keep the messages from disappearing but when i refresh , it still disappears -
My EBS healty status is degraded as a result of initial wrong configuration
i initially tried to deploy my Django app with EBS several times and it failed. I then investigated and discovered from the logs that the django.config file in my .ebextensions had the wrong settings instead of ‘‘‘option_settings: aws:elasticbeanstalk:container:python: WSGIPath: myapp.wsgi:application ‘‘‘ I used the one on the documentation which was ‘‘‘option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application ‘‘‘ Now whenever I try to redeploy again after making this change I still get the 502 Bad Gateway on the browser and in the logs it still says this ‘‘‘ ModuleNotFoundError: No module named 'ebdjango'. ‘‘‘ I deleted my .elasticbeanstalk file and tried to create another application with a different name which shows up in the config.yml in the .elasticbeanstalk, but I still get the 502 error and the logs showing ModuleNotFoundError: No module named 'ebdjango' -
How do i pass the variable from django views.py to my javascript?
Sure, here's a Markdown version of your question for Stack Overflow: Issue with Passing Data from Django Views to JavaScript in Template I'm trying to pass data from my Django view to JavaScript in my template, but I'm encountering an issue where the parameters I'm passing appear to be empty when I inspect the webpage. Views.py def homepage(request): selected_model = request.GET.get('model', '') if selected_model == '1': df = pd.read_csv(os.path.join(settings.BASE_DIR, 'files', 'data', 'preprocessed_price_optimization_dataset.csv')) model_path = os.path.join(settings.BASE_DIR, 'files', 'data', 'price_optimization_model.h5') X = df[['product_id', 'category_id', 'brand_encoded', 'historical_price_scaled']] y = df['historical_price'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) loaded_model = load_model(model_path) predictions = loaded_model.predict(X_test) evaluation = loaded_model.evaluate(X_test, y_test) actual_data = [1, 2, 3, 4, 5] predicted_data = [6, 7, 8, 9, 10] context = { 'actual_data': actual_data, 'predicted_data': predicted_data, } else: print("no actual and predicted data") context = {} return render(request, 'base.html', context) base.html <select id="visualSelector" name="model" onchange="printSelectedValue({{ actual_data|safe }}, {{ predicted_data|safe }})"> <option value="0">---</option> <option value="1">SCATTERPLOT</option> <option value="2">LINEPLOT</option> </select> JavaScript function printSelectedValue(actualData, predictedData) { var selectedValue = document.getElementById('visualSelector').value; var selectedModelValue = document.getElementById('modelSelector').value; if (selectedModelValue === '0') { console.log("No model selected"); return; } var canvas = document.getElementById('plotCanvas'); if (selectedValue === '0') { canvas.style.backgroundColor = 'red'; console.log("value 0:", actualData); } else if (selectedValue … -
How to customize response api schema with drf-spectacular for Django Rest Framework
I have a problem of customizing API schema. Here is my case: I need to return a list of instances in my serializer with it's fields, but also there is supposed to be one common aggregation field, that accumulates those model instances in a list. Here is the example of json structure: { "comments_amount": 2, "comments": [ { "id": 0, "card_id": 0, "user_id": 0, "text": "Comment", "created_at": "2024-02-24T09:07:43.946Z", "updated_at": "2024-02-24T09:07:43.946Z" }, { "id": 1, "card_id": 0, "user_id": 0, "text": "Comment", "created_at": "2024-03-24T09:07:43.946Z", "updated_at": "2024-03-24T09:07:43.946Z" } ] } Here is my code for serializer: class CommentResponseSerializer(serializers.ModelSerializer): parent_id = serializers.IntegerField(help_text=_("ID of parent comment"), min_value=0, required=False) card_id = serializers.IntegerField(help_text=_("Product's card ID"), min_value=0) user_id = serializers.IntegerField(help_text=_("ID of user who created this comment"), required=True) class Meta: model = Comment exclude = ["user", "parent", "card"] And here is for views: @extend_schema(tags=["Product Cards"], summary="API для комментариев карточек продуктов") class CommentView(APIView): @extend_schema( description="API для просмотра комментариев. Доступно всем пользователям.", parameters=[ OpenApiParameter( name="card_id", description="ID карточки продукта", required=True, type=int, location="path" ) ], request=CommentInputSerializer, responses=CommentResponseSerializer, ) def get(self, request, *args, **kwargs): card_id = kwargs["card_id"] comments = Comment.objects.filter(card_id=card_id) serializer = CommentResponseSerializer(comments, many=True) data = { "comments_amount": comments.count(), "comments": serializer.data } return Response(data, status=status.HTTP_200_OK) Here, as you can see, I create dict with … -
Don't insert modules inside a container
I decided to deploy a test project and bought a vps server on ubuntu from reg ru for this purpose. When building containers, an error occurs with pip packages inside the python image: > [backend 5/6] RUN pip install -r requirements.txt: #0 15.76 WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ #0 31.37 WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ #0 47.48 WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ #0 64.58 WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ #0 83.69 WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/asgiref/ #0 98.81 ERROR: Could not find a version that satisfies the requirement asgiref==3.7.2 (from versions: none) #0 98.81 ERROR: No matching distribution found for asgiref==3.7.2 ------ failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 1 root@cv3598657:/home/var/www/test_repo# client_loop: send disconnect: Broken pipe the image code itself and … -
Why am I getting WebKitFormBoundary in my post request using the JS Fetch API?
I am trying to send data to my Django server from JS. My code looks like this? let url = play_selected.dataset.url; const csrf_token = getCookie('csrftoken'); let data = JSON.stringify( { selects: arr } ); console.log(data); const response = await fetch(url, { method: 'POST', // Specify the HTTP method body: data, // JSON.stringify(data), // Convert data to JSON string (if object) headers: { 'Content-Type': 'application/json', // Set content type header 'X-CSRFtoken': csrf_token } }); data = await response.json(); console.log(data); The selects arr is just an array of numbers which I will eventually do something in my django back end. Currently all I am doing is printing out the request.POST variable which is always empty. When I print out request.body I get the following: (Pdb) p request.POST <QueryDict: {}> (Pdb) p request.body b'{"selects":["29"]}' (Pdb) I would imagine that request.POST should display something similar to what is in request.body. Why is request.POST empty? -
How to read PDF file from Django?
I need to create an app in Django that scrape data from a PDF file, how can I do this? I really don't have any clue all I know is that python has a few libraries to read PDF files like for example PYPDF2 but I don't know how to integrate all of this in DJANGO. I tried PYPDF2 in a python shell but it didn't work for me all it prints is blank line -
Django CORS issue
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://url/. (Reason: header ‘authorization’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response). The api is made using djangorestframework and i have configured corsheader in the settings.py,error pop up when im trying to put authorization in headers in the fetch request -
Lots of issues using openAI in Python only on Ubuntu
I have a project utilising openAI One of the changes required me to run openai migrate, it says "You can run openai migrate to automatically upgrade your codebase to use the 1.0.0 interface. " I did that on windows and had no issues. I can't remember how I did it. I think I just opened up powershell or terminal and wrote openai migrate (which doesn't really make sense to me, is it scanning my entire system and makes changes to update the code? Whatever, I digress). Anyway, I'm moving to linux and ran my program (Django). It says the exact same thing as before - that you need to run openai migrate. So I open a terminal on my desktop, 'openai migrate' and viola..nothing. OpenAI not found. I know that openai is installed in ./local after trying to follow another debugging step. It seems I have 2 options 1 - manually refactor my code to comply with the new API or 2 - run the openAI migrate command which I believe does that already for you?? Anyway, I'm going with option #2 but I cannot even run open ai migrate. I'm not a linux expert (yet..) and don't know about … -
Is the structure of the project correct?
Here is the structure of my project: ├─── applications │ ├─── about │ │ ├─── admin.py │ │ ├─── api │ │ │ │ └─── __init__.py │ │ │ ├─── apps.py │ │ ├──── __init__.py │ │ ├─── libs │ │ │ │ └─── __init__.py │ │ │ ├─── migrations │ │ │ │ └─── __init__.py │ │ ├─── models.py │ │ │ ├─── services │ │ │ │ └─── __init__.py │ │ ├─── templates │ │ ├─── tests.py │ │ │ └─── views.py │ ├─── account │ │ │ ├─── admin.py │ │ ├─── api │ │ │ │ └─── __init__.py │ │ │ ├─── apps.py │ │ ├──── __init__.py │ │ ├─── libs │ │ │ │ └─── __init__.py │ │ │ ├─── migrations │ │ │ │ └─── __init__.py │ │ ├─── models.py │ │ │ ├─── services │ │ │ │ └─── __init__.py │ │ ├─── templates │ │ ├─── tests.py │ │ │ └─── views.py │ ├─── blog │ │ │ ├─── admin.py │ │ ├─── api │ │ │ │ └─── __init__.py │ │ │ ├─── apps.py │ │ ├──── __init__.py │ │ ├─── libs │ │ │ │ └─── __init__.py │ │ │ …