Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue uploading files to S3 in Django on Azure App Services
Our application has been hosted on Heroku for several years without any issues uploading to S3. We are working on migrating to Azure App Services. We are now encountering an issue where the the file uploads are failing. They appear to be timing out and cause the gunicorn worker to abort and close. The server log and stack trace hasn't been helpful, but I'm hoping someone else may see something here that can be useful. None of the storage configuration or settings have been modified from Heroku to Azure. packages being used: Django==3.2.25 boto3==1.35.9 botocore==1.35.9 s3transfer==0.10.2 django-storages==1.14.4 Settings: DEFAULT_FILE_STORAGE = 'project.utils.storage.HashedFilenameMediaS3Boto3Storage' Storage class - this storage class setup was implemented about 8 years ago so maybe I need to make some changes?: def HashedFilenameMetaStorage(storage_class): class HashedFilenameStorage(storage_class): def __init__(self, *args, **kwargs): # Try to tell storage_class not to uniquify filenames. # This class will be the one that uniquifies. try: new_kwargs = dict(kwargs) #, uniquify_names=False) super(HashedFilenameStorage, self).__init__(*args, **new_kwargs) except TypeError: super(HashedFilenameStorage, self).__init__(*args, **kwargs) def get_available_name(self, name): raise NoAvailableName() def _get_content_name(self, name, content, chunk_size=None): dir_name, file_name = os.path.split(name) file_ext = os.path.splitext(file_name)[1] file_root = self._compute_hash(content=content, chunk_size=chunk_size) # file_ext includes the dot. out = os.path.join(dir_name, file_root + file_ext) return out def _compute_hash(self, content, chunk_size=None): … -
How to Resolve the Issue: Django with Visual Studio Code Changing Template Without Effect?
I have a Django app, and I am using Visual Studio Code as my editor. I have implemented functionality for recovering passwords via an email template. I edited the template to see what effect it would have on the email, but the changes had no effect. I even deleted the email template, but I still received the old email template in my inbox. The email template is within a folder named templates in my account app. Here is my email template (password_reset_email.html): <!-- templates/password_reset_email.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Password Reset Request</title> <style> /* Add any styles you want for your email */ </style> </head> <body> <p>Je hebt om een wachtwoord reset aanvraag gevraagd voor je account.</p><br><p> Klik de link beneden om je wachtwoord te veranderen:</p> <p>Als je niet om een wachtwoord reset hebt gevraag, neem dan contact op met:</p> <br><p> test@test.nl. En klik niet op de link.</p> <p>Met vriendelijke groet,<br>Het app team</p> </body> </html> But in my email box I still got this email: Dag test gebruiker , Je hebt om een wachtwoord reset aanvraag gevraagd voor je account. Klik de link beneden om je wachtwoord te veranderen: Reset je wachtwoord Als je niet om een wachtwoord … -
Django channels stops working after some time
I have a system that has two forms of communication, one through http connections for specific tasks and another through websockets for tasks that require real-time communication. For the deployment I used nginx, daphne and redis, these are the configurations: Service [Unit] Description=FBO Requires=fbo.socket After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/var/www/api.fbo.org.py/backend Environment="DJANGO_SETTINGS_MODULE=fbo-backend.settings" ExecStart=/var/www/api.fbo.org.py/backend/.venv/bin/daphne \ --bind 127.0.0.1 -p 8001 \ fbo-backend.asgi:application [Install] WantedBy=multi-user.target Nginx server { server_name api.fbo.org.py; access_log /var/log/nginx/access.log custom_format; location /static/ { alias /var/www/api.fbo.org.py/backend/staticfiles/; expires 86400; log_not_found off; } location /media/ { root /var/www/api.fbo.org.py/backend; expires 86400; log_not_found off; } location / { proxy_pass http://localhost:8001; proxy_set_header Host $host; proxy_set_header X-Real_IP $remote_addr; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://127.0.0.1:8001; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } Library versions channels==4.0.0 channels-redis==4.2.0 daphne==4.1.2 Django==3.2.25 Reviewing the log when the system crashes I found that the following is repeated for different actions performed on the system: WARNING Application instance <Task pending name='Task-3802' coro=<ProtocolTypeRouter.__call__() running at /var/www/api.bancodeojos.org.py/backend/.venv/lib/python3.8/site-packages/channels/routing.py:62> wait_for=<Future pending cb=[shield.<locals>._outer_done_callback() at /usr/lib/python3.8/asyncio/tasks.py:902, <TaskWakeupMethWrapper object at 0x7f93a6c84c70>()]>> for connection <WebRequest at 0x7f93a6754b80 method=PUT uri=/turns/9141/ clientproto=HTTP/1.0> took too long to shut down and was killed. I tried changing the versions of the libraries, … -
Django formtools' "done" method is not getting called on form submission
I am trying to build a multistep html form using Django formtools. I have 2 forms with 2 fields at most. After filling the last form (i.e. step 2) and clicking the submit button, I am taken back to step 1 instead of the "done" method being called. And the whole thing just becomes a never ending loop. Here is my code. forms.py class ListingForm1(forms.Form): company_name = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={ 'class': 'form-control', })) address = forms.CharField(max_length=500, required=True, widget=forms.TextInput(attrs={ 'class': 'form-control', })) class ListingForm2(forms.Form): business_category = forms.ModelChoiceField(queryset=BusinessCategory.objects.all(), required=True, widget=forms.Select(attrs={ 'id': 'cat-select', 'class': 'form-control', })) views.py class AddListing(SessionWizardView): form_list = [ListingForm1, ListingForm2] template_name = 'registration/listing_templates/addlisting.html' def done(self, form_list, form_dict, **kwargs): return HttpResponse("form submitted") {% extends "base.html" %} {% load static %} {% load i18n %} {% block head %} {{ wizard.form.media }} {% endblock %} {% block css %} <!-- <link href="{% static 'dashboard_assets/css/custom.css' %}" rel="stylesheet"> --> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <style> #div_id_2-allkws{ display: none !important; } .select2{ width: 100% !important; } .select2-container .select2-selection--single{ height: calc(2.68rem + 2px) !important; } .select2-container--default .select2-selection--single .select2-selection__arrow{ top: 10px !important; } </style> {% endblock css %} {% block content %} <div class="content-container container"> {{ form.media }} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" … -
I need to sum same amount field for day and month in django query
class MyModel(models.Model): amount = models.FloatField() datetime = models.DateField() and MyModel have some types like card and p2p and other so I need to give in query SUM(amount)and filter(type=some_type ) and also I need full amount for month [. full_amount: ......, { "datetime_date": "2024-08-15", "terminal": "0.00", "cash": "0.00", "p2p": "0.00", "bank": "400000.00", "other": "0.00" }, { "datetime_date": "2024-08-28", "terminal": "100000.00", "cash": "200000.00", "p2p": "0.00", "bank": "0.00", "other": "0.00" } ] if I -
I'm stuck in creating a Django custom user model, I added my app to settings, created superuser but when I login it fails
Here is the code, it fails to login on admin even after doing all necessary migrations from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('users must have an email address') email = self.normalize_email(email) email = email.lower() user = self.model(email=email, name=name) user.set_password(password) user.save(using=self._db) return user #def create_user(self, email, name, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_agent', False) extra_fields.setdefault('is_business', False) extra_fields.setdefault('is_personal', True) return self.create_user(email, name, password=None, **extra_fields) def create_personal(self, email, name, password=None): user = self.create_user(email, name, password) user.is_personal = True user.save(using=self._db) return user def create_agent(self, email, name, password=None): user = self.create_user(email, name, password) user.is_agent = True user.save(using=self._db) return user def create_business(self, email, name, password=None): user = self.create_user(email, name, password) user.is_business = True user.save(using=self._db) return user def create_superuser(self, email, name, password): user = self.create_user(email, name, password=password) user.is_superuser = True user.is_active = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser, PermissionsMixin): USER_TYPE = ( ('personal', 'is_personal'), ('agent', 'is_agent'), ('business', 'is_business'), ('staff', 'is_staff'), ('superuser', 'is_superuser') ) type = models.CharField(choices=USER_TYPE, default='personal', max_length=255) email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_personal = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) is_business = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = … -
Django with Signoz opentelemetry Tracing issue
I am trying to setup signoz for my Django project, but I have hit a dead end and now I am not able to proceed further, so I request you to help me out with this case. SigNoz Steps Requirements Python 3.8 or newer for Django, you must define DJANGO_SETTINGS_MODULE correctly. If your project is called mysite, something like following should work: export DJANGO_SETTINGS_MODULE=mysite.settings Step 1 : Add OpenTelemetry dependencies In your requirements.txt file, add these two OpenTelemetry dependencies: opentelemetry-distro==0.43b0 opentelemetry-exporter-otlp==1.22.0 Step 2 : Dockerize your application Update your dockerfile along with OpenTelemetry instructions as shown below: ... # Install any needed packages specified in requirements.txt # And install OpenTelemetry packages RUN pip install --no-cache-dir -r requirements.txt RUN opentelemetry-bootstrap --action=install # (Optional) Make port 5000 available to the world outside this container (You can choose your own port for this) EXPOSE 5000 # Set environment variables for OpenTelemetry ENV OTEL_RESOURCE_ATTRIBUTES=service.name=<SERVICE_NAME> ENV OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.{REGION}.signoz.cloud:443 ENV OTEL_EXPORTER_OTLP_HEADERS=signoz-access-token=<SIGNOZ_TOKEN> ENV OTEL_EXPORTER_OTLP_PROTOCOL=grpc # Run app.py with OpenTelemetry instrumentation when the container launches CMD ["opentelemetry-instrument", "<your_run_command>"] ... <your_run_command> can be python3 app.py or python manage.py runserver --noreload After following the above steps I've setup my django project accordingly, I've shared the my project changes below. Dockerfile FROM … -
Django filtering by annotated field
I'm trying to sort only those objects that contain arrays in the JSON field class Rule(models.Model): data = models.JSONField() class JsonbTypeof(Func): function = 'jsonb_typeof' Rule.objects.annotate(type=JsonbTypeof("data")).filter(type="array") But this query always returns an empty queryset However, if you call Rule.objects.annotate(type=JsonbTypeof("data")).values("type") then the expected queryset with a set of objects is returned: <QuerySet [{'type': 'object'}, {'type': 'object'}, {'type': 'array'}, {'type': 'array'}]> And if you do like this: Rule.objects.annotate(type=Value("array")).filter(type="array") Then the filtering is done correctly Are there any experts who can tell me how to filter and leave only arrays? -
Auto-generated DRF route *-detail not found while using ViewSets
I try to use Django Rest Framework (DRF) with HyperlinkedModelSerializers, ViewSets and a Routers. When I check the generated routes, Django shows me vehicle-detail, but DRF complains with an error: ImproperlyConfigured at /api/vehicles/ Could not resolve URL for hyperlinked relationship using view name "vehicle-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. The code below works well if a leave out the url from fields. Anyone an idea what is missing? urls.py from rest_framework.routers import DefaultRouter from vehicles import viewsets # Create a router and register our ViewSets with it. router = DefaultRouter() router.register(r'vehicles', viewsets.VehicleViewSet, basename='vehicle') # The API URLs are now determined automatically by the router. urlpatterns = [ path('', include(router.urls)), ] vehicles/viewsets.py class VehicleViewSet(viewsets.ModelViewSet): queryset = Vehicle.objects.all() serializer_class = VehicleSerializer vehicles/serializers.py class VehicleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Vehicle fields = ['url', 'name', 'description'] # fields = ['name', 'description'] # Removed 'url'. Now the API works Generated URLs api/ ^vehicles/$ [name='vehicle-list'] api/ ^vehicles\.(?P<format>[a-z0-9]+)/?$ [name='vehicle-list'] api/ ^vehicles/(?P<pk>[^/.]+)/$ [name='vehicle-detail'] api/ ^vehicles/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='vehicle-detail'] api/ [name='api-root'] api/ <drf_format_suffix:format> [name='api-root'] -
Django LoginView It doesn't show any error if I enter wrong input
im using django built in authentication but when im enter wrong email or password no errors comes up views.py from django.contrib.auth.views import LoginView,LogoutView class Login(LoginView): redirect_authenticated_user = True login.html <form method ="post"> {% csrf_token %} {% for field in form %} <div class="form-group"> {{ field.errors }} {{ field.label_tag }} {{ field }} {{field.help_text }} </div> {% endfor %} <button type="submit" class="btn ">تایید</button> </form> output in browser so i expect if i enter email dose not exist in database tell me user not exist or if i enter wrong password show me a error message says wrong password consol log [30/Aug/2024 02:49:04] "POST /auth/login/ HTTP/1.1" 200 7144 Not Found: /favicon.ico [30/Aug/2024 02:49:05,079] - Broken pipe from ('127.0.0.1', 58248) -
Python, Django, Creating table model insert data
How can I correct the numbers in a table that lists ID numbers one by one in numerical order using Python and Django? Would you be polite and help me please guys i have no idea even if i deleted them all the next one goes with highest numbers up and so on -
MetabaseDashboardAPIView groups and dashboard and i am not still created any groups and dashboard for MetabaseDashboardAPIViewRoots
MetabaseDashboardAPIView groups and dashboard and i am not still created any groups and dashboard for MetabaseDashboardAPIViewRoots MetabaseDashboardAPIView groups and dashboard and i am not still created any groups and dashboard for -
Django I can't access the Image.url of the ImageField object
Hey im new in django and Im playing with uploading and showing images here. I have a model product : class Product(models.Model): title = models.CharField("Title",max_length=50) description = models.CharField("Description",max_length=200) active = models.BooleanField("Active",default=False) price = models.IntegerField("Price",default=0) stock = models.IntegerField("Stock",default=0) discount = models.IntegerField("Discount",default=0) date_created = models.DateTimeField("Date Created",auto_now_add=True) image = models.ImageField(null=True,blank=True ,upload_to="images/product/") def __str__(self): return self.title when Im retrieving this model using Product.objects.all(), and do for prod in products : print(prod.image.url) it returns error : The 'image' attribute has no file associated with it. but when im doing single query : Products.object.get(pk=5), I can access the image.url. I wonder why this happens tho. My english is bad so I hope I delivers it well. -
Datadog Integration with Azure App Service doesnt work
Summary of problem I have a django application which is containerised and running on Azure app service and I am having trouble sending traces to datadog. I have been stuck on this issue for a while and cant seem to solve it 2024-08-30T07:45:27.7503477Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries, 1 additional messages skipped 2024-08-30T07:45:33.5918905Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries 2024-08-30T07:45:46.1090952Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries 2024-08-30T07:46:08.9280102Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries 2024-08-30T07:46:12.7362637Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries 2024-08-30T07:46:20.2283515Z failed to send, dropping 2 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries 2024-08-30T07:47:03.2944981Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries, 3 additional messages skipped 2024-08-30T07:47:13.1601344Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries, 4 additional messages skipped 2024-08-30T07:48:02.5895355Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries, 2 additional messages skipped 2024-08-30T07:48:04.6799632Z failed to send, dropping 1 traces to intake at http://127.0.0.1:8126/v0.5/traces after 3 retries, 9 additional … -
How to do Markdown-like custom text to HTML formatting in Django?
My aim is to get text input, pass it through regex to turn it into HTML tags, and then safely display that HTML. Something like this: It's <script> *Bold*...! @sysop! which becomes, rendered faithfully, It's &lt;script&gt; <span class="f-b">Bold</span>...! @<a class="f-at" href="/user/123">sysop</a>! (It doesn't have to be exactly this, this is just an example.) Note that my output is able to grab values like the user sysop and get the user instance's URL /user/123 from the database - a good solution should be free enough to allow things like this. What I'm looking for is not specifically Markdown. What I'm looking for is the ability to do custom regex filters as shown above. If there is a way to do this, or even a package that allows me to do that (and remove/disable the existing Markdown/BBCode/etc. filters), that would be really great. -
How to integerate Saleor in my Django project
I have an existing Django project that I've been working on, and I'm interested in integrating the Saleor dashboard as an app within this project. Ideally, I would like to access the Saleor dashboard through a route like backend/. Additionally, I want to connect the Saleor dashboard with my existing product database. I already have a fully responsive frontend built with HTML and CSS that displays products and other related information. My goal is to integrate all the features of Saleor, such as checkout, payment processing, and other e-commerce functionalities, into my current project without needing to start a new project. How can I achieve this integration while maintaining my existing frontend and backend structure? Any guidance or suggestions on how to approach this would be greatly appreciated! -
HTML page to PDF using pdfkit in python django returning blank
I am trying to convert an html file to pdf after passing and populating it with some data. But it is returning a blank white page.I am using pdfkit and django and below is my code. def generate_pdf(data): """ Convert HTML content to PDF. """ html_string = render_to_string('timeline_template.html', {'data': data}) pdf_file = pdfkit.from_string(html_string, False) return pdf_file Also below is the html page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Timeline Report</title> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic' rel='stylesheet' type='text/css'> <style> body { margin: 0; padding: 0; background: rgb(245,245,245); color: rgb(50,50,50); font-family: 'Open Sans', sans-serif; font-size: 14px; line-height: 1.6em; } /* Timeline container */ .timeline { position: relative; width: 80%; margin: 0 auto; margin-top: 20px; padding: 1em 0; list-style-type: none; } /* Vertical line on the left */ .timeline:before { content: ''; position: absolute; left: 40px; top: 0; width: 2px; height: 100%; background: rgb(230,230,230); } /* Individual timeline items */ .timeline li { padding: 20px 0; position: relative; } /* Circle markers */ .timeline li:before { content: ''; position: absolute; left: 31.5px; top: 24px; width: 16px; height: 16px; border-radius: 50%; background: white; border: 2px solid rgb(0,0,0); } .timeline li .desc ul{ margin-left: 0; padding-left: 0; list-style: none; } .timeline li .desc … -
how to copy/paste blocks in wagtail(wagtail into existing django project)
i try to understand requirements and know the possible methods and the wagtail project is using wagtail-modeltranslation, here is the requirements: "Main purpose of this is to speed up making new pages, and the translation from EN to NL. Now, when we make a nice series of blocks in EN, we need to rebuild them all for the NL version, which is annoying. If we can copy and paste the blocks from the EN version into the NL version, we only need to replace the actual texts, not all the images, sliders, caroussels, etc etc." i want to understand and do solution like how to copy blocks from EN version to NL version??? and how should handle the problem(with clear steps). i hope sbd will solve my dream!!! -
how to use the ‘problems’ field in pycharm?
pycharm keeps finding ‘problems’ in the project. it's all completely useless and unfounded. don't know how it works. does anyone use it ? for example, here he found an ‘indent expected’ problem and here's the code: class ProductForm(forms.ModelForm): or here, there's a mistake in the middle of nowhere. code: And so on throughout the project. found 18 errors, looked through each one - all to no avail. is it me who doesn't know how to use it, or it doesn't work? does anyone use it? -
How check if user is logged in on server side React, Django, JWT
I have set up authorization using the JWT token. Now I want to give the user access to the protected view, which requires authorization. class GetUser(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def post(self, request): return Response({'username': request.user.username}) How do I check if the user is logged in on the server side? I wrote an asynchronous function that accesses the django rest framework api. But this function always returns a promise no matter what I do. function saveToken(data) { localStorage.setItem('access_token', data.access) localStorage.setItem('refresh_token', data.refresh) return true } async function isLoggedIn() { return await axios.post('api/getuser/', {}, {headers: {Authorization: 'Bearer ' + localStorage.getItem('access_token')}}) .then(async function (response) { return true }) .catch(async function (error) { return await axios.post('api/token/refresh/', {refresh: localStorage.getItem('refresh_token')}) .then(async function (response) { return saveToken(response.data) }) .catch(async function (error) { return false }) }) } As I understand it, I can't get the value from promise in any way. That's why I decided to write the component this way, but React throws an error. const ComponentMainArea = () => { const location = useLocation() const element = useOutlet() return isLoggedIn().then((value) => { if (!value) { return (<Navigate to="/proxy/8000/login"/>) } else { return ( <div className='mainarea'> <AnimatePresence mode='wait' initial={true}> {element && React.cloneElement(element, { key: … -
https to http nginx works partially
I can use http and https connection to my router(to which connected server) through KeenDNS. I have nginx with following config on the server server { listen 80; server_name example.com; location /static/ { alias /app/staticfiles/; } location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } so when I go to /static/ urls over https everything works, but / urls doesn't and I'm getting 400 bad request. Btw I'm having Django in docker with gunicorn behind proxy_pass's web url. Over http everything works fine. What could be the problem? -
Supporting Apple sign-in for mobile and web using dj_rest_auth, allauth
We are looking to implement Apple sign-in from both the web and mobile using this stack. React SPA using Django 4.2 / DRF 3.15.2 / dj_rest_auth 6.0.0 / allauth 0.61.1 backend Due to the different Client ID for web and mobile, we had to configure two separate apps in SOCIALACCOUNT_PROVIDERS[”apple”] as recommended by allauth. To make this work for the version we are using, we had to manually apply the following patch to 0.61.1 and set the “hidden” property on the mobile app. My impression was that this property is needed to make it work with some admin interface, but maybe not. The explanation is not clear - “For the app specifying the bundle ID, add the following to the settings so that this app does not show up on the web”. We use the same settings for both APPS - secret, key, settings, except for client_id. When we set this property, the “hidden” app (mobile) never gets used and we get a client_id mismatch error when logging in from mobile. So I guess I am not sure I understand the purpose of having that property. Or maybe we are missing some other patch(es) that make this work. In short, … -
Memory Leak When Using Django Bulk Create
I have the following code that constantly checks an API endpoint and then if needed, adds the data to my Postgres database. Every iteration of this loop is leaking memory in the postgresql\operations.py file. Im not sure what data is still being referenced and isnt clearing, so realistically what could be causing this issue? class DataObject(models.Model): raw_data = models.TextField() name = models.TextField(null=True) def post_process(self): data = json.loads(self.raw_data) self.name = data['name'] def do_from_schedule(): api = API() loads = api.grab_all_data() del api datas_to_create = [] for load in loads: data = DataObject() data.raw_data = json.dumps(load) data.post_process() datas_to_create.append(data) DataObject.objects.bulk_create(datas_to_create, ignore_conflicts=True, batch_size=200) del datas_to_create gc.collect() while True: do_from_schedule() time.sleep(5) Here are the results of tracemalloc. Theres a consistent, and unending memory leak. #1: postgresql\operations.py:322: 156.9 KiB return cursor.query.decode() #1: postgresql\operations.py:322: 235.3 KiB return cursor.query.decode() #1: postgresql\operations.py:322: 313.7 KiB return cursor.query.decode() #1: postgresql\operations.py:322: 392.0 KiB return cursor.query.decode() #1: postgresql\operations.py:322: 470.4 KiB return cursor.query.decode() I found this for someone using MySql https://stackoverflow.com/a/65098227/8521346 But im not sure how to even test/ fix this if it was the issue with the postgres client. -
How to use Bootstrap Theme of dashboard in Django admin?
i am new in django , i want to create my own custom admin panel for django project ,i have a bootstrap theme of dashoard and i want to make this as admin panel for my project ,how to do this ,can i do this by overriding the existing admin files like 'admin/base.html' ,'admin/base_site.html', or is there any other method to do this...Please Guide i am trying to over ride the existing file ,is there any other method, also need some guidance about the urls, if i have to use another method then over riding the existing file -
ModuleNotFoundError: No module named, how come no model was named since it is written in the main code and in the model?
I created this model code but the django makemigrations command doesn't work and show an error. The first code is where the database should be and where I put the name of the model I want, the second code is how the model is made so far and the last is the error that appears when I try to use makemigrations. I have no idea what to do to make it work. ``INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'livros'` `from django.db import models class Livros(models.Model): nome = models.CharField(max_length = 100) autor = models.CharField(max_length = 30) co_autor = models.CharField(max_length = 30) data_cadastro = models.DateField() emprestado = models.BooleanField(default=False) nome_emprestado = models.CharField(max_length = 30) data_emprestimo = models.DateTimeField() data_devolução = models.DateTimeField() tempo_duração = models.DateField()` File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked ModuleNotFoundError: No module named 'livros'