Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why am I getting TypeError: string indices must be integers, not 'str' on Django Deserialization?
I'm trying out using AJAX to implement tags for Book Blog posts. I want to use TDD to check and make sure that they filter properly but am running into issues. Mainly when I try and Deserialize the JSONResponse content, it throws an error when I try and iter through it. error message: File "E:\04_projects\01_Python\10_book_blog\venv\Lib\site-packages\django\core\serializers\json.py", line 70, in Deserializer yield from PythonDeserializer(objects, **options) File "E:\04_projects\01_Python\10_book_blog\venv\Lib\site-packages\django\core\serializers\python.py", line 111, in Deserializer Model = _get_model(d["model"]) ~^^^^^^^^^ TypeError: string indices must be integers, not 'str' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\04_projects\01_Python\10_book_blog\posts\tests\test_views.py", line 103, in test_returns_filtered_posts for obj in decereal: File "E:\04_projects\01_Python\10_book_blog\venv\Lib\site-packages\django\core\serializers\json.py", line 74, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError test case that makes the error: def test_returns_filtered_posts(self): # makes one post with a tag and one post without t1 = Tag.objects.create(tag_name='test', group_name='general') p1 = Post.objects.create(book_title='test_book') p2 = Post.objects.create(book_title='test_book2') p1.tags.add(t1) # simulates clicking the 'test' tag response = self.client.post(reverse('ajax_post'), {'tag[]': ['test', 'general']}) # decerealizes the data decereal = deserialize('json', response.content) # print for debugging for obj in decereal: print(obj) # bad test case but not getting this far self.assertNotIn(p2, decereal) The view that is called: def ajax_call(request): data = serializers.serialize('json', Post.objects.all()) # … -
Django: how select items that do not have referencies from other items?
Assume, we have a model: class Critters(models.Model): name = models.CharField() parent = models.ForeignKey(Critters, blank=True, null=True, on_delete=models.CASCADE) In begin was some critters: id Name Parent == ======== ======== 0 Critter1 1 Critter2 2 Critter3 And then, some critters made a children: id Name Parent == ======== ====== 0 Critter1 1 Critter2 2 Critter3 3 Child1 0 4 Child2 1 I wand make a request for select all parents without childrens (i.e. no creatures with parents, and no parents with existing childrens): id Name Parent == ======== ====== 2 Critter3 I think it can be done with annotate and exact django's directives, but i'm dubt in stick how exactly i can make this... UPDATE1 Ofcourse, critter and child in field Name just for example, we can't filter table by Name. -
Image file not being uploaded to media file
I'm trying to display an input type="file" that accepts image files. When i upload the file through Django Admin, everything works (its uploaded to my media folder, and its successfully displayed on html) but when i do it through my html page, it doesnt go to media, and i can't display it. So i'm assuming the problem isnt with django but my settings.py or something with my html HELP create.html (to upload image) <label for="imgpreview" class="imglabel">Choose Image</label> <input accept="image/*" type='file' id="imgpreview" name="imgpreview" class="image-form" onchange="previewImage(event);"/> index.html (to display image) <div class="banner-image"><img id="model-img-display" src="{{item.image.url}}"></div> views.py (to save model) def create(request): if request.method == 'POST': title = request.POST['title'] image = request.POST['imgpreview'] category = request.POST['category'] brand = request.POST['brand'] color = request.POST['color'] clothes = Clothes(title=title, image=image, category=category, brand=brand, color=color) clothes.save() return render(request, "wardrobe/create.html") models.py class Clothes(models.Model): title = models.CharField(max_length=50) image = models.ImageField(default='', upload_to='wardrobe/') #wardrobe= media subfolder category = models.CharField(max_length=200, null=True, blank=True) brand = models.CharField(max_length=200, null=True, blank=True) color = models.CharField(max_length=200, null=True, blank=True) deleted = models.BooleanField(default=False) settings.py MEDIA_URL='/media/' MEDIA_ROOT= BASE_DIR/'project5'/'wardrobe'/'media' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('wardrobe.urls')), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) EDIT: i changed my views.py following https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html instructions and now everything works! -
No reverse match with comments
I want to display my comment form in my page. However, every time i enter the page i get no reverse match error. Maybe there is something to do with form action, but honestly I have no idea what to do. Please help! views.py def single_blog(request, pk): news = News.objects.filter(pk=pk) comment_form = CommentForm() context = { 'title': 'Новость', 'news': news, 'comment_form': comment_form } return render(request, 'blog/single-blog.html', context) def save_comment(request, pk, new_pk): form = CommentForm(request.POST) if form.is_valid(): form.instance.new_id = new_pk comment = form.save() return redirect('single-blog', pk) models.py class Comments(models.Model): post = models.ForeignKey(News, on_delete=models.CASCADE) author = models.CharField(max_length=255, verbose_name='Автор') text = models.TextField(max_length=255, verbose_name='Текст') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Дата публикации') urls.py path('single-blog/<int:pk>', single_blog, name='single-blog'), path('save_comment/<int:pk>', save_comment, name='save_comment') html Leave a Reply <form class="form-contact comment_form" action="{% url 'save_comment' new_pk %}" id="commentForm"> {% csrf_token %} <div class="row"> <div class="col-sm-6"> <div class="form-group"> {{ comment_form.author }} </div> </div> <div class="col-12"> <div class="form-group"> {{ comment_form.text }} </div> </div> </div> -
VSCode debugpy with dockerized django app
I'm trying to use debugpy with a dockerized django app - it connects momentarily then disconnects - I'm not sure why docker-compose.backend.yml: (the uplifty service below is the django server I want to attach to from vscode) version: '3' services: db: image: postgres platform: linux/amd64 container_name: uplifty-db environment: - POSTGRES_HOST_AUTH_METHOD=trust ports: - "5432:5432" uplifty: build: context: . dockerfile: ./docker/Docker.server/Dockerfile image: uplifty env_file: .env container_name: uplifty volumes: - .:/code ports: - "8000:8000" - "5678:5678" depends_on: - db links: - db:postgres Dockerfile: FROM python:3.11.3 ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install -y \ sudo && apt-get install -y \ git \ nginx \ postgresql-client \ supervisor RUN mkdir /code ADD docker /code RUN rm /etc/supervisor/supervisord.conf && \ ln -s /code/docker/Docker.server/supervisord.conf /etc/supervisor/supervisord.conf && \ rm /etc/nginx/nginx.conf && \ ln -s /code/docker/Docker.server/nginx.conf /etc/nginx/nginx.conf && \ mkdir -p /var/log/supervisor && \ mkdir -p /var/log/gunicorn && \ mkdir -p /code/logs/supervisord RUN groupadd -r app -g 1000 && \ useradd -u 1000 -r -g app -d /code -s /bin/bash -c "Docker image user" app RUN chown -R app:app /code && \ chown -R app:app /var/run && \ chown -R app:app /var/log/gunicorn RUN pip install psycopg2 RUN pip install poetry RUN pip install gunicorn ADD server/pyproject.toml … -
Django 4 Running some python codes/files outside views for specific request and returning the parameters as context before rendering template
I am relatively new to Django, while I am fine with loading static pages etc, I have an issue with complex dynamic content. I am designing a quiz, when a user answers a question, I would like to log some parameters into the database (correct or wrong, time taken for the response, etc). When the user clicks next, I want to analyse the data from the answer to the previous question, apply an algorithm and select the question and its parameters as context to the template so that the next question is loaded. So far, I have created a config.py that lets me take the parameters (context) from quiz.py and use them in views.py. Both config.py and quiz.py are in the main folder of the Quiz App. The problem I have is how to read and analyse the user session and data in my quiz.py so that I could apply the algorithm based on the user's previous answers and performance on the database. I have looked at many forums, videos, etc but not even sure if I am on the right path. I have looked at Middleware, Threading, using Celery, etc and I cannot get the user data from "request" … -
Django Define serializer for Model in relation using Foreign Key
I am having 3 models, Site which basically contains Site Details, Comments which contains the the comments and replies to a particular site and Files which contains all the attachments. I wanted to get all the necessary fields from Comments and Files Model, for which I am trying to use a Serializer in Site Details Models. Below is my models.py - **Site:** site = models.CharField(max_length=30, blank=False, null=False) approver = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="design_site_approver", blank=True, null=True) submitter = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="design_site_submitter", blank=True, null=True) **Files** site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name='site_name') **Comment** user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_name_comment') timestamp = models.DateTimeField(default=datetime.datetime.now) remarks = models.TextField(null=True, blank=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='replies') site = models.ForeignKey(Site, on_delete=models.CASCADE, related_name='site_name_comment') My Serializer.py file are: **Comment** class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' **Files** class FileSerializer(serializers.ModelSerializer): class Meta: model = Files fields = '__all__' **Site** class SiteSerializer(serializers.ModelSerializer): remarks = CommentSerializer(many=True,read_only=True) attachment = FileSerializer(many=True,read_only=True) class Meta: model = Site fileds = '__all__' I am unable to get the Values of Files and Comment object, but I am not getting any error as well. What is the solution for this -
How to move django models from one app to another
So we have a django backend already in production with a reasonable amount of data.During the initial stages, we had a small team of two and we were also working with deadlines. I would also admit we were beginners and didn't follow best practices.Because of this,all our models were defined in one app.Now the project is messy and I also learnt it is not a good practice to have many models in one app.Now my question is,how can we move some of this models to new different apps in our project without running into migration issues or worse loosing the data? Our models also have a lot of relationships.Just for reference,we are using postgres databases. I have reasearched the internet for solution but haven't found a comprehensive approach to doing it.Most of the answers here also seems outdated.Some people also recommend to use south which is deprecated. -
I cannot get a list of CSV files and their headers at the same time
from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from .models import CSVFile from .serializers import CSVFileSerializer import csv ... class CSVFileListView(APIView): def get(self, request, format=None): files = CSVFile.objects.all() file_data = [] for file in files: columns = self.extract_columns(file) # Извлекаем информацию о колонках file_data.append({ 'id': file.id, 'filename': file.file.name, 'uploaded_at': file.uploaded_at, 'columns': columns # Добавляем информацию о колонках в список файлов }) return Response(file_data, status=status.HTTP_200_OK) def extract_columns(self, file): with open(file.file.path, 'r', encoding='utf-8') as csv_file: csv_reader = csv.reader(csv_file) columns = next(csv_reader, []) # Извлекаем первую строку, содержащую заголовки колонок return columns class CSVFileDetailView(APIView): def get(self, request, file_id, format=None): try: file = CSVFile.objects.get(id=file_id) with open(file.file.path, 'r', encoding='utf-8') as csv_file: dialect = csv.Sniffer().sniff(csv_file.read(1024)) csv_file.seek(0) csv_data = list(csv.reader(csv_file, dialect=dialect)) columns = csv_data[0] data = csv_data[1:] response_data = { 'columns': columns, 'data': data } return Response(response_data, status=status.HTTP_200_OK) except CSVFile.DoesNotExist: return Response({'error': 'File not found'}, status=status.HTTP_404_NOT_FOUND) Error occurred while getting the list of all files using GET: UnicodeDecodeError at /api/v1/csv/files/ 'utf-8' codec can't decode byte 0xa4 in position 14: invalid start byte Request Method: GET Request URL: http://127.0.0.1:8000/api/v1/csv/files/ Django Version: 4.1.5 Exception Type: UnicodeDecodeError Exception Value: 'utf-8' codec can't decode byte 0xa4 in position 14: invalid start byte Exception Location: , line 322, … -
form element is not valid
I'm trying to make a form (without using django's template forms) but for some reason my forms are never valid when I try them. Here is my code: forms.py: class AddressForm(forms.Form): address_long = forms.CharField(max_length=500) class Meta: model = Address fields = ['address_long'] def save(self, commit=True): address = Address.objects.create() address.address_long = self.cleaned_data['address_long'] if commit: address.save() return address views.py: @login_required def add_address_view(request): if request.method == 'POST': form = AddressForm(request.POST) print(request.POST) if form.is_valid(): print("Valid") address = form.save() user_profile = request.user.userprofile user_profile.addresses.add(address) # Add to many to many field user_profile.save() return redirect('core:profile') # Redirect to the user's profile page else: form = AddressForm() return render(request, 'Test_site/add-address.html', {'form': form, 'countries': COUNTRIES}) And my html looks like this: ... <form method="POST" class="col-md-5 border-right"> {% csrf_token %} ... <div class="col-md-12"> <label class="labels">Address Long</label> <input name="{{ form.address_long.name }}" id="{{ form.address_long.auto_id }}" type="text" class="input-field form-control" placeholder="enter address line" value=""> </div> ... </form> When I try this on my local host I get this output from the print statements in the view function: <QueryDict: {'csrfmiddlewaretoken': ['my_generated_token'], 'address_long': ['Long address try']}> But no matter what I do it just doesn't pass the '.is_valid()' check. Also I can't look up on what 'form' holds, like trying to do form.cleaned_data['address_long'] causes a 'form … -
django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
I'm trying to get a queryset of unique values. Here is my model class Data_agent_account(models. Model): data_agent = models.ForeignKey(Data_agent, null=False, on_delete=models.PROTECT) date_entered = models.DateTimeField(db_index=True) type = models.BooleanField(null=False) # debit=False & credit=True amount = models.DecimalField(max_digits=12, decimal_places=2, null=True) desc = models.CharField(max_length=255) paid_on = models.DateTimeField(db_index=True, null=True, blank=True) class Meta: ordering = ['date_entered', ] In my view, I'm trying for da_list = Data_agent_account.objects.filter(paid_on__isnull=True).order_by('data_agent').distinct('data_agent') for da in da_list: print(da) The error I get is : django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("data_agent_data_agent_account"."data_ag... The SQL that works is: SELECT DISTINCT(data_agent_id) FROM data_agent_data_agent_account WHERE paid_on is null; -
How to use form data to render a certain view.py function in Django
I am working on this harvardCS50 project where I have to redirect the user to the article page if their search query meets the dictionary key. I have stored the articles as 'text' and headings as 'head in the dictionary. data = { "textone": {"head": "Title one", "text": "This will be text ONE."}, "texttwo": {"head": "Title two", "text": "This will be text TWO."} } I was able to make article links that render the requested data, but I have not been able to do it through the form data. If the user input meets the key in my dictionary, the html should render the data based on that. I have been stuck on it for 2 days, kindly help. <head> <title>{% block title %} {% endblock %}</title> </head> <body> <nav> <form action="" method="GET"> <input type="text" name="q"> <input type="submit"> </form> <ul> {% for key, value in data.items %} <a href="{% url 'wikiApp:entry' key %}"><li> {{ value.head }} </li></a> {% endfor %} </ul> </nav> {% block body %} {% endblock %} </body> Following is my views.py: def intro(request): context={"data": data} return render(request, 'wiki/layout.html', context=context) def title(request, entry): for name in data: if name == entry: return render(request, 'wiki/content.html', { "head": data[name]['head'], "text": … -
I'm Tetando shows some fields in my template plus I come across this error in Forms [closed]
django.core.exceptions.FieldError:Unknown field(s)(produtos) specified for Product e aqui esta o codigo: class SelecaoProdutoForm(forms.ModelForm): class Meta: model = Product fields = ('produtos',) widgets = { 'produtos':forms.CheckboxSelectMultiple } estou querendo mostra os produtos que tenho e junto deles vim um checkbox para mim selecionar -
How to add a Bootstrap modal to edit the item selected?
I'm a beginner Django programmer and I have this project that is about creating timelines in which you can add events, and these events will show up in their timelines along with either a countdown to when it will start, a counter of how long ago it ended, or a countdown of how much time it has until it ends if it's an ongoing event. Here's the project's repository: https://github.com/high-rolls/timely So far I was able to handle timeline creation, edit and deletion, as well as event creation and displaying timelines and events within a timeline. But I started having trouble when trying to allow the user to edit an event on the list, what I wanted to do was display a Bootstrap modal, like the one I already display when adding a new event but for editing one, and I wanted to have only a single edit modal element at the bottom of the page (instead of adding a modal after each event's div). Should I do this with JavaScript to dynamically pass the ID of the selected event and fetch the data of that event to fill up the modal's form? I am also confused whether I should use … -
How to cache a TensorFlow model in Django
In Django, I have this TensorFlow model: model = predict.load_model('path\model.h5') After the model is loaded, I want to keep it in memory such that I can use it multiple times without constantly reloading it. I tried using the cache like this: model = predict.load_model('path\model.h5') cache.set('model', model) when I try to retrieve it by: cache.get('model') I get this error: Unsuccessful TensorSliceReader constructor: Failed to find any matching files for ram://cf101767-7409-47ba-8f98-0921cc47a20a/variables/variables You may be trying to load on a different device from the computational device. Consider setting the experimental_io_device option in tf.saved_model.LoadOptions to the io_device such as '/job:localhost'. Is there a different approach to keeping the model loaded ? -
Poetry and Django project 'HTTPResponse' object has no attribute 'strict' [closed]
Education case: on Windows 10 system in VSCode after successful poetry init I have problem with this error, while adding dependencies I know I need later on. Any ideas to fix? -
Can IIS read an exe file of my dynamic web application?
If I convert my django code into an executable file and host it on IIS, will IIS be able to read and execute the code and keep running my dynamic web application (which is accessible to the internet) If yes, I want to know how to achieve such scenario? Please help me out Thanks in advance I want IIS to be able to read obfuscated code or code which is converted to executable file. I want step by step process to achieve this -
Django simple_history query : type object has no attribute 'history'
First of all sorry for my English, I will try my best. I've 2 model; Post and PostComment. And I want show history of comments or history of post on the frontend. When I try to this I'm getting the error : type object has no attribute 'history' Here is my models: models. py from django.db import modelsfrom autoslug import AutoSlugField from simple_history.models import HistoricalRecords from ckeditor.fields import RichTextField class Post(models.Model): Date = ... EditedDate = ... Published = models.BooleanField(default=False) Sender = models.ForeignKey(User, on_delete=models.CASCADE) Title = models.CharField(max_length=200) Text = RichTextField() def __str__(self): return self.Title class PostComment(models.Model): Date = ... EditedDate = ... Comment_Sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='yorum') Post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='yorumlar') Comment = models.TextField() Published = models.BooleanField(default=False) History = HistoricalRecords() # new line def __str__(self): return self.YorumGonderen.pers_fullName def save(self, *args, **kwargs): if self.Published == False: self._change_reason = 'Comment is not Approved' else: self._change_reason = 'Comment is Approved' return super().save(*args, **kwargs) and my admin.py from simple_history.admin import SimpleHistoryAdminclass CommentHistoryAdmin(SimpleHistoryAdmin): list_display = ['CommentSender','Comment','Post','Published', 'EditedDate','id'] history_list_display = ['status']search_fields = ['CommentSender'] admin.site.register(Post, CommentHistoryAdmin) I can get all the history records I want but I need to show those records on the page Here is what I am try: def viewPostDetail(request, Slug): Post = … -
Django - OGP Image url preview works inconsistently
I've been struggling with this issue for the past few days now and I still can't find the root cause of it so here it goes: I have a Django blog for which I would like to be able to share links in social media apps such as Whatsapp, Telegram and Signal and I would like these links to have previews containing images of the blog post that the user is sharing. Following the OGP standard I added these meta tags to my page: <meta property="og:image:url" content="{% block meta_img_url_preview %}{% endblock %}"/> <meta property="og:image" content="{% block meta_img_preview %}{% endblock %}"/> <meta property="og:image:secure_url" content="{% block meta_img_secure_preview %}{% endblock %}"/> <meta property="og:image:width" content="1200"/> <meta property="og:image:height" content="630"/> <meta property="og:type" content="article"/> <meta property="og:locale" content="ro_RO"/> After setting up those meta tags, it seems that sharing links via the Whatsapp Web app or the Signal desktop app the image preview shows up just fine. However when using the mobile app and sharing links, only the title and description show up and the image is not being displayed. After checking my server's logs I can see that the requests for the image preview are served just fine with a status of 200: Example of request made using … -
Python django manytomanyfield не получается получить категории
views.py enter image description here models.py enter image description here html enter image description here сайн enter image description here Такая вот тема: я создал две модели ArticlesCategory и Articles, где они связанный полем ManyToManyField. По идее я должен был в файле views передавать все объекты Articles, в html пройтись по нему циклом (что уже работает) а также извлекать список категорий, что приписаны статьям и выводить их через запятую после TAG. Но у меня не выходит. Кто поможет -
"Definition of service not found" error when using pg_service.conf file with Django and PostgreSQL
I'm trying to use a pg_service.conf file to manage database connections in my Django application, but I'm running into an error when trying to connect to the database using the named service. Here's what my DATABASES setting in Django looks like: python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'service': 'my_service' } } } And here's what my pg_service.conf file looks like (located at /etc/postgresql-common/pg_service.conf): ini [my_service] host=localhost port=5432 user=my_user password=my_password dbname=my_database However, when I try to run my Django application, I get the following error: psycopg2.OperationalError: service file "/etc/postgresql-common/pg_service.conf" not found The above exception was the direct cause of the following exception: django.db.utils.OperationalError: definition of service "my_service" not found I've checked that the pg_service.conf file exists in the correct location and has the correct permissions, and I've also verified that the service name in my DATABASES setting matches the service name in pg_service.conf. What else could be causing this error? Any help would be greatly appreciated! What I've tried: Verified that the pg_service.conf file exists in /etc/postgresql-common/ and has the correct permissions (owned by postgres user with 0640 permissions). Verified that the service name in my DATABASES setting matches the service name in pg_service.conf. Restarted my Django … -
What is the difference between data and instance in serializer?
When should we use the 'data' instead of 'instance'? serializer = ModelSerializer(data=queryset) serializer = ModelSerializer(instance=queryset) Possibly, this is a beginner question, but I have not found a worthy resource to fully understand serializers. I appreciate it if you describe how to use a ModelSerializer in action. -
How do I render a htmx response using typing effect in Django just like ChatGPT does?
I'm building a book summarizer app as a personal project with Django and I make API requests to OpenAI. The user enters the book name and author and gets the summary of the book. I'm using htmx for the form submission to avoid page refresh. I'm rendering the summary in a container/textbox. I want to implement a loader effect as soon as the user clicks on the "Submit" button and when the response is ready, it should be rendered with a typing effect and the container should also increase as the texts being rendered increase by line. Everything works but the texts don't get rendered using typing effect as I want and also the loader effect starts loading as soon as I open the page not when the user clicks on the submit button. I guess my problem is in the Javascript code. Thanks in advance! Here are my codes: Views.py from django.shortcuts import render import os, openai, json from django.http import JsonResponse, HttpResponse openai.api_key = os.get(OPENAI_API_KEY) # Create your views here. def index(request): result = None if request.method == 'POST': book_name = request.POST.get('book_name') author = request.POST.get('author') prompt = f'Write a summary of the book titled: {book_name} written by {author}. … -
Macbook M2 ImportError: dlopen(_mysql.cpython-310-darwin.so, 0x0002): symbol not found in flat namespace '_mysql_affected_rows'
I am setting up local workspace for my Django project with MySQL on a Macbook AIR with M2 chip. All config are migrated from my old Macbook Pro with core i7 using OSX Migration Assistant. I am having problem trying to run server on my local, i.e. python manage.py runserver. The err msg is: File "/Users/.../.venv/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/.../.venv/lib/python3.10/site-packages/MySQLdb/__init__.py", line 24, in <module> version_info, _mysql.version_info, _mysql.__file__ NameError: name '_mysql' is not defined MySQL server is set up on my local and works fine. I am able to use mysql to connect to my local MySQL server, i.e. mysql -u root -p mysqlclient is installed, the version is 2.1.1 While importing MySQLdb directly using python console, it seems python is having difficulty using dlopen to open the "c compiled" (not sure how this is called exactly) file, or it opened but there was error? Error as: Python 3.10.6 (v3.10.6:9c7b4bd164, Aug 1 2022, 17:13:48) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb Traceback (most recent call last): File "/Users/.../.venv/lib/python3.10/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/.../.venv/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so, 0x0002): symbol not found in flat namespace … -
How to download tensorflow models in a nginx docker gunicorn django webapp?
I have an nginx docker gunicorn django web app that requires some models to be downloaded from tensorflow, but, as people may see, the current configuration does not allow enough time for it to be downloaded. My current gunicorn file (may not be a problem, because it should give time enough, but somehow it doesn't): bind = '0.0.0.0:8000' workers = 60 timeout = 3600 module = 'production.wsgi' chdir = '/app' forwarded_allow_ips = '*' proxy_allow_ips = '*' In the development stage, prior to this production stage, there was no problem in waiting a first long download to have this files locally. Now in production, the container gives me this error. Downloading (…)lve/main/config.json: 100%|██████████| 571/571 [00:00<00:00, 2.67MB/s] Downloading model.safetensors: 4%|▍ | 52.4M/1.34G [00:20<08:25, 2.56MB/s] [2023-07-16 05:45:06 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:7) site.com.br_1 | [2023-07-16 02:45:06 -0300] [7] [INFO] Worker exiting (pid: 7) Downloading model.safetensors: 4%|▍ | 52.4M/1.34G [00:21<09:02, 2.38MB/s] site.com.br_1 | [2023-07-16 05:45:07 +0000] [138] [INFO] Booting worker with pid: 138 What is the correct approach? I think I need to force the download, probably thru the Dockerfile file ahead, but i cannot grasp how to do it, so how to correctly download this files and, to be more precise, from …