Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can Django fixtures be used for production?
I have a Django application that reads different CSV files and saves them to the same model/table in the DB. While fixtures are certainly used for setting up a test environment quickly, I used the fixture to configure the different CSV Schemata that is subsequently parsed by the Django application. So each of the data provider has their own distinct schema which is a different row in the CsvSchema table. During code review it came up that this is bad style because -- It leads to duplication of data. I found it useful to pass such configurations via a fixture and treated it like a configuration file. To further treat the fixture like a configuration file, I even put it inside the git repository, which is again somethong the reviewer agrees with. The reviewer also claimed that fixtures should be use only once in the lifetime of the application, while setting it up initially. To me, the fixtures are just a tool that Django provides us. I can play around with the schema details in my development machine, and then dump them into a fixture, effectively using it as configuration. Am I playing too hard and fast with the rules … -
Model instances without primary key value are unhashable with Djongo
I am getting the error Model instances without primary key value are unhashable when trying to remove a model instance from my admin panel. models.py from djongo import models import uuid PROPERTY_CLASSES = ( ("p1", "Video Property"), ("p2", "Page Property"), ("trait", "Context Trait"), ("custom", "Custom Property") ) EVENT_TYPES = ( ("video", "Video Event"), ("track", "Track Event"), ("page", "Page Event") ) class Device(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) class Platform(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) app_name_possibilities = models.TextField(blank=True) class EventPlatformDevice(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = "" event_field = models.ForeignKey('Event', on_delete=models.CASCADE) applicable_apps = models.ManyToManyField('Platform', blank=True) applicable_devices = models.ManyToManyField('Device', blank=True) property_group = models.ManyToManyField('PropertyGroup', blank=True) custom_properties = models.ManyToManyField('Property', blank=True) class Event(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, unique=True) event_type = models.CharField(max_length=20, choices=EVENT_TYPES) class PropertyGroup(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) applicable_properties = models.ManyToManyField('Property') class Property(models.Model): _id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) property_class = models.CharField(max_length=20, choices=PROPERTY_CLASSES) format_example = models.TextField(blank=True) notes = models.TextField(blank=True) The issue lies with the EventPlatformDevice model I believe. The issue I think is when I create a new entry in the Admin panel and setup the relationships between EventPlatformDevice.applicable_apps it gets saved into the MongoDB using a _id:ObjectId("61c25d36cdca07c8a6101044") … -
App Engine running Django not logging on prod service
I am running Django application on Google App Engine standard env. I have two services running for dev and prod. both services plus my local machine are configured with Google Logging Client for logging. Recently, for some reason, the prod service stopped posting logs into StackDriver. But both my local and dev service are posting logs. here is my code: settings.py from google.cloud import logging if os.getenv('GAE_APPLICATION', None): client = logging.Client() else: # setup for my local logging. client = logging.Client.from_service_account_json('PATH TO JSON FILE') LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'stackdriver': { 'level': 'INFO', 'class': 'google.cloud.logging.handlers.CloudLoggingHandler', 'client': client }, 'console':{ 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'mail_admins': { 'level': 'CRITICAL', 'class': 'django.utils.log.AdminEmailHandler', "email_backend": "anymail.backends.mailgun.EmailBackend" } }, 'loggers': { 'django': { 'handlers': ['stackdriver'], 'propagate': True, 'level': 'INFO', }, 'django.request': { 'handlers': ['stackdriver', 'console', 'mail_admins'], 'level': 'INFO', 'propagate': True, }, } } urls.py def trigger_error(request): import logging logger = logging.getLogger('stackdriver') logger.error('test error') logger.critical('test critical') logger.warning('test warning') logger.info('test info') division_by_zero = 1 / 0 path('debug/', trigger_error), My questions are: Is there any limits or quotes for logging into a specific … -
ModelFormset save failing
I've created a web app that presents a set of questionnaires. I have different models for Question, Questionnaire, Answer and Response that acts as an intermediate table. I have created the modelFormset and rendered the form, but when I try to save I get a null value constraint, because I'm not passing in the question_id but I am at a loss of how I should be doing it. null value in column "question_id" violates not-null constraint Models.py class Questionnaire(models.Model): title = models.CharField(max_length=50, blank=False, unique=True) class Question(models.Model): questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE) sequence = models.IntegerField() question = models.TextField() class Response(models.Model): project_name = models.ForeignKey(Project, on_delete=models.CASCADE) questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE) user = models.CharField(max_length=50, blank=True) class Meta: constraints = [ models.UniqueConstraint(fields= ['project_name','questionnaire'], name='unique_response'), ] class Answer(models.Model): RAG_Choices = [ ('Green', 'Green'), ('Amber', 'Amber'), ('Red', 'Red') ] question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=50, blank=True, choices=RAG_Choices) notes = models.TextField(blank=True) response = models.ForeignKey(Response, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=['question','response'], name='unique_answer'), ] view.py def get_questionnaire(request, project_id, questionnaire_id): # Get the Response object for the parameters response = Response.objects.get( project_name_id=project_id, questionnaire_id=questionnaire_id ) AnswerFormSet = modelformset_factory(Answer, form=AnswerForm, fields=('answer','notes',), extra=0) answer_queryset = Answer.objects.filter(response=response ).order_by('question__sequence' ).select_related('question') if request.method == 'POST': form = AnswerForm(request.POST) answers = form.save(commit=False) answers.project_name_id = response answers.save() return … -
How to get value from Django BigAutoField
Tyring to get a value out of django.db.models.fields.BigAutoField for reference. I can't seem to convert it to a int and if I convert to a str I just get (<django.db.models.fields.BigAutoField>,). I've tried to find some documentation but can't seem to see any way of getting a value out. -
I am trying to add an active class to my nav bar items on my website when clicked
I want to add the active class to the navbar item that I click on, on my website. In my JS code, it tells the program what class to look under ("nav-item"). Then it tells my program to remove the active class from the current active class, and then add the active class to the class that was clicked. I'm assuming the logic is correct but I most likely missed syntax. I am new to HTML and JS so any help would be greatly appreciated. HTML Code: <ul class="navbar-nav"> <li class="nav-item"><a class="nav-link js-scroll-trigger active" href="#about">About</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#education">Education</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#experience">Experience</a></li> <li class="nav-item"><a class="nav-link js-scroll-trigger" href="#skills">Skills</a></li> </ul> JS code: $('.nav-item').on('click', '.nav-link js-scroll-trigger', function () { $('.nav-link js-scroll-trigger active').removeClass('active'); $(this).addClass('active'); }); -
Convert pandas.core.series.Series data from nan to None Django
I have a pandas.core.series.Series class When the field is empty I get 'nan' as a value and like that it stores in database. I want to convert that empty value to 'None' so I can manipulate with None value What I tried is here import numpy as np data.replace(np.nan, None, regex=True) But this isn't working. Can someone help me please? -
Adding {% csrf_token %} to javascript insertion
All, I have a popup that is inserted via javascript when a button is clicked: function loadTypeManagement(existingDocTypes) { const typeManagementModalDiv = '<div class="modal fade" id="typeManagementModalDiv" >' + '<div class="modal-dialog" style="max-width: none;">' + '<div class="modal-content feedback_popup" style="height:100%; margin-top: 0vh;">' + '<form class="feedback_form" autocomplete="off" action="/" method="post" id="taskitem_form">' + '<h1 id="djangoInsert">Type Management</h1><br>' + '<hr>' + '<div class="autocomplete container justify-content-center">' + '<h3 style="margin-bottom: .5vw;">Add a Document Type</h3>' + '<hr style="width: 50% ;margin: auto; margin-bottom: .5vh;">' + '<div class="row">' + '<div class="col-3"></div>' + '<label class="col-6 admin_input_desc ">Document Type:</label>' + '<div class="col-3"></div>' + '</div>' + '<div class="row">' + '<div class="col-3"></div>' + '<input class=" text-center col-6 admin_input " id="addDoctypeId" type="text" name="addDocTypeName" placeholder="Document Type">' + '<div class="col-3"></div>' + '<div class="d-inline p-2 text-white ">' + '<p class="col-sm-4 admin_input_desc d-inline">Can this new type be an Authentication Source?</p>' + '<label class="">No</label>' + ' <input type="radio" id="date_newToOld" name="choice" value="date_newToOld" checked/>' + '<label class="float-right " style="margin-left: 1.25vw;">Yes</label>' + ' <input class="float-left" type="radio" id="date_newToOld" name="choice" value="date_newToOld" />' + '</div>' + '</div>' + '<input class="submit_button" name="submit" type="submit" value="Add Document Type">' + '</div>' + '</form>' + '<form class="feedback_form" autocomplete="on" action="/action_page.php">' + '<hr>' + '<div class="autocomplete container justify-content-center">' + '<h3 style="margin-bottom: .5vw;">Remove a Document Type</h3>' + '<hr style="width: 50% ;margin: auto; margin-bottom: .5vh;">' + '<div class="row">' + … -
Django-autocomplete-light - "No results found" in browser on startup - after doing one search in admin - results are found in browser again
I have a peculiar problem with Django-autocomplete-light. When I go to my browser and try searching for something I get "no results found" - but when I go to the admin panel and add a model, the results pop up as they should. When I have done this one time, I can go back to the browser and then the results show up as they should. I'm suspecting some caching issue, but not sure how to debug this. Maybe someone can take a look if there is something wrong with my set-up. models.py class DogBreeds(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Advertisement(SoftDeleteModel, TimeStampedModel): breed = models.ForeignKey(DogBreeds, on_delete=models.CASCADE, null=True, verbose_name='Hundras') views.py class BreedAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return DogBreeds.objects.none() qs = DogBreeds.objects.all() if self.q: qs = qs.filter(name__icontains=self.q) return qs Form template {% extends '_base.html' %} {% load static %} {% block content %} <form method="post" enctype="multipart/form-data" id="adForm" data-municipalities-url="{% url 'ajax_load_municipalities' %}" data-areas-url="{% url 'ajax_load_areas' %}" novalidate> {% csrf_token %} <table> {{ form.as_p }} </table> <button type="submit">Publish</button> </form> </body> {% endblock content %} {% block footer %} {% comment %} Imports for managing Django Autocomplete Light in form {% endcomment %} <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> <link rel="stylesheet" … -
Django rest_framework MVC structure
I'm currently working on a Django project, using the rest_framework. The project is built around API endpoints the client-side will use to send/retrieve data about features such as users, players, playerInventory etc etc. My question is, I'm struggling to structure this project and I'm not sure if i should be destructuring the data my front-side receives. The data I'm working with looks like API ENDPOINT Returns a single player inventory [GET] { "elementId": 1, "elements": [1, 2, 3 ,4] } API ENDPOINT Update a single player inventory [POST] from -> { "elementId": 1, "elements": [1, 2, 3 ,4] } (example) to -> { "elementId": 1, "elements": [3, 3, 3 ,1] } I'd like to be able to use a front-end 'model' concenpt that takes the data from my API fetches and constructs them for me so i can use that data in a better manor. Could someone give me a detailed Django project file structure and some Javascript model code design patterns possible? here's my models.py: class User(models.Model): userId = models.AutoField(primary_key=True) username = models.CharField(max_length=16) email = models.EmailField(max_length=30) isMember = models.BooleanField(default=False) class meta: db_table = 'app_users' app_label = "app" managed = True def __str__(self): return str(self.userId) class Player(models.Model): playerId = models.ForeignKey(User, … -
Django Admin upload image with foreign key
I have a model Product with a User and ProductImages as foreign key. models.py class User(AbstractBaseUser): ... class ProductImages(models.Model): image_type = models.CharField(max_length=33,default='image_type') image_file = models.ImageField( upload_to='images/', null=True, blank=True, default='magickhat-profile.jpg' ) class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) productimages = models.ForeignKey(ProductImages, on_delete=models.CASCADE) product_title = models.CharField(max_length=255, default='product_title') product_description = models.CharField(max_length=255, default='product_description') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) product_view = models.IntegerField(default=0) def __str__(self): return self.product_title def get_absolute_url(self): return reverse('product_change', kwargs={'pk': self.pk}) forms.py class ProductForm(ModelForm): productimages = forms.ImageField() CHOICES_STATUS = (('Pronto', 'Pronto'),('Em obras', 'Em obras'),('Lançamento', 'Lançamento'),) product_status = forms.ChoiceField(choices=CHOICES_STATUS) product_title = forms.CharField() product_description = forms.CharField() class Meta: model = Product fields = '__all__' admin.py class AdminProductModel(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(user_id=request.user) kadmin.register(User, UserAdmin) kadmin.register(Product, AdminProductModel) But in the admin Product model the field for image is redering as select field no ImageField My purpose is add a upload image field on django model administration. If i use ImageField direct on Product model the field is redering ok, but i need a external table to store that image becouse is a multimage upload, so i need a foreing key. How is the right way to that purpose. I see other questions about that, but the majority is old versions, and … -
How do I set up a nested URL pattern for /category/subcategory/post in Django?
I've looked through several answers and I cannot seem to figure out how to do this. My best guess is this has something to do with all of these answers are specific to writing function based views. The problem: I have a portal where I want the URL structure to be: /portal/engagement/engagement_name/finding/finding_name So I've tried several things and this is the closest I can get: urlpatterns = [ path('', login_required(CustomerDashboard.as_view()), name='portal_dashboard'), path('engagement/add', login_required(EngagementCreateView.as_view()), name='engagement_create'), path('engagement/<slug:slug>/', login_required(EngagementDetailView.as_view()), name='engagement_detail'), path('engagement/<slug:slug>/edit', login_required(EngagementUpdateView.as_view()), name='engagement_update'), path('engagement/<slug:slug>/finding/add', login_required(FindingCreateView.as_view()), name='finding_create'), path('finding/<slug:slug>', login_required(FindingDetailView.as_view()), name='finding_detail'), path('finding/<slug:slug>/edit', login_required(FindingUpdateView.as_view()), name='finding_update'), ] If I try to do something like engagement/<slug:slug>/finding/<slug:slug>/ it just errors. I've tried to follow some answers like choosing the slug field (i.e. slug:engagement_slug``` but none of it works. I'm using class based views. My models are: Company Engagement (FK to Company) Finding (FK to Engagement) I'm not sure what other code I can provide to help. I've read some other options on overriding the get_object method and passing the slug as a **kwarg. I'm just not sure what is the "right" way to do this. -
Django Update AbstractUser
IntegrityError at / NOT NULL constraint failed: pages_profile.username Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.2.9 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: pages_profile.username How do I update an abstractuser that's already signed in? from django.shortcuts import redirect, render from .forms import UserProfileForm from .models import Profile def index(request): context = {} if request.method == "POST": print(request.POST) form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): img = form.cleaned_data.get("avatar") obj, created = Profile.objects.update_or_create( username=form.cleaned_data.get('username'), defaults={'avatar': img}, ) obj.save() print(obj) return redirect(request, "home.html", obj) else: form = UserProfileForm() context['form']= form return render(request, "home.html", context) -
Django - Given time zone, month and year get all post created on that date in that time zone
So I have this Post model. I want to be able to retrieve all posts that were created in a month, year under a certain time zone. model.py class Post(models.Model): uuid = models.UUIDField(primary_key=True) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator") body = models.CharField(max_length=POST_MAX_LEN) So for example if a user creates 10 posts in November, 2 in December of 2021 in PST. Then I have a view that takes month, year and time_zone and let's say the url looks something like /post/<int:month>/<int:year>/<str:time_zone> and the user pings /post/11/2021/PST then it should return the 10 posts from November. How do I return all posts from a month and year in a time zone given time zone, month and year? Setup: Django 3.2.9 Postgresql -
Django pluralize person as people
trying to output the correct plural value in Django template when count is more than 1. <p>{{ review.markers.helpful.count }} person{{ reviews.markers.helpful.count|length|pluralize }} found this helpful</p> still returns 1 persons or 2 persons instead of 1 person and 2 people any help to fix this in the template? -
Django server does not start with docker-compose up
I dockerize my django backend app. I am using posgresql as db. After doing docker-compose up the last logs are: db_1 | 2021-12-21 18:39:58.213 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2021-12-21 18:39:58.213 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2021-12-21 18:39:58.310 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2021-12-21 18:39:58.476 UTC [42] LOG: database system was shut down at 2021-12-21 18:39:58 UTC db_1 | 2021-12-21 18:39:58.678 UTC [1] LOG: database system is ready to accept connections I am not getting any other logs after them,I don't know what the issue is maybe its due to postgresql. But django server is not starting. I did docker ps I got following results CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d92379ca89b7 prodlerbackend_prodler "python manage.py ru…" 20 minutes ago Up 20 minutes 0.0.0.0:8000->8000/tcp, :::8000->8000/tcp prodlerbackend_prodler_1 3364c1cda344 postgres:11.2-alpine "docker-entrypoint.s…" 20 minutes ago Up 20 minutes 0.0.0.0:5432->5432/tcp, :::5432->5432/tcp prodlerbackend_db_1 I think the containers are up, still Django server is not started what can be the issue? docker-compose.yml version: "3.9" services: db: image: postgres:11.2-alpine volumes: - ./postgres-data:/var/lib/postgresql/data environment: - HOST=localhost - POSTGRES_DB=prodler - POSTGRES_USER=postgres - POSTGRES_PASSWORD=admin123 ports: - 5432:5432 prodler: build: context: … -
Error 415 on angular although the headers are up
I'm getting error 415 on angular api request but http header are set: login.service.ts: var httpHeaders = new HttpHeaders(); httpHeaders.set('Content-Type', 'application/json'); httpHeaders.set('Access-Control-Allow-Origin', '*'); return this.httpClient.post<any>(requestUrl, params, { headers: httpHeaders }) As backend i used django rest framework Any idea ? Thans in advance. -
Multiple concurrent requests in Django async views
From version 3.1 Django supports async views. I have a Django app running on uvicorn. I'm trying to write an async view, which can handle multiple requests to itself concurrently, but have no success. Common examples, I've seen, include making multiple slow I/O operations from inside the view: async def slow_io(n, result): await asyncio.sleep(n) return result async def my_view(request, *args, **kwargs): task_1 = asyncio.create_task(slow_io(3, 'Hello')) task_2 = asyncio.create_task(slow_io(5, 'World')) result = await task_1 + await task_2 return HttpResponse(result) This will yield us "HelloWorld" after 5 seconds instead of 8 because requests are run concurently. What I want - is to handle multiple requests to my_view concurrently. async def slow_io(n, result): await asyncio.sleep(n) return result async def my_view(request, *args, **kwargs): result = await slow_io(5, 'result') return HttpResponse(result) I expect this code to handle 2 simultaneous requests in 5 seconds, but it happens in 10. What am I missing? Is it possible in Django? -
Django background task like FastAPI
I have a requirement that I need to calculate hash of some images in background after the data inserted on DB tables. I saw FastAPI Vs Django implementation of background task and it seems very easy and feasible solution for background task implementation in FastAPI comparing to Django. So I need to know is there similar kind of implementation on Django available or not? because it's seems too much on Django for a simple background task. OR It would be better to use simple multiprocessing.Process For Django: I need to do these steps for achieve background task Installation I like [pipenv][1] so: > cd [my-django-project root directory] > pipenv install django-background-tasks Now add 'background_task' to INSTALLED_APPS in settings.py: INSTALLED_APPS = ( # ... 'background_task', # ... ) and perform database migrations to ensure the django-background-tasks schema is in place: > pipenv shell (my-django-project) bash-3.2$ python manage.py migrate Creating and registering a Task Any Python function can be a task, we simply need to apply the @background annotation to register it as such: from background_task import background @background(schedule=10) def do_something(s1: str, s1: str) -> None: """ Does something that takes a long time :param p1: first parameter :param p2: second parameter … -
How to run only the tests that are affected by the latest changes in a Django project?
We are running Django tests on a bitbucket pipeline and it takes a bit long. What I want to do is, get the diff between the current branch and the main branch and run the tests that are affected by this diff. How can I do that? -
what is the correct way to filter data from db in monthly and yearly basis for analytics?
I am making an analytics section for my client, where I need to display data in graphical form. For this I am using chart js. Now I have a model to store visitors of the website. Now I want to filter the data in monthly and yearly basis to put it in chart js and display it graphically. Now what I am doing is this monthly_visitor = VisitorCount.objects.all().filter(date_of_record__month = today.month).count() yearly_visitor = VisitorCount.objects.all().filter(date_of_record__year = today.year).count() Here, I am able to get the count for my current month and year. But making variables for each month and year is not the right to do it. So please suggest me what is the correct procedure to filter the data so that I can make the analytics. I have never before done this, so I do no the correct approach, please suggest me. Also the chart js code looks like this, which also perhaps no the correct way to do make the analytics const vismonth = document.getElementById('visitorMonthly').getContext('2d'); const visitorMonthly = new Chart(vismonth, { type: 'bar', data: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], datasets: [{ label: 'Visitors Monthly', data: [12, 19, 3, 5, 2, 3], backgroundColor: … -
How to update page in django without page refresh?
So.I have prices in database django,when I change it,prices on website dont change and I have to restart django server.So..How Can I refresh page in django without restart django server? -
django.db.utils.ConnectionDoesNotExist: The connection prueba doesn't exist
I want migrate Django database to MongoDB with Djongo but i have this error. Traceback (most recent call last): File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/db/utils.py", line 167, in ensure_defaults conn = self.databases[alias] KeyError: 'prueba' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 74, in handle connection = connections[db] File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/db/utils.py", line 199, in __getitem__ self.ensure_defaults(alias) File "/home/alexsaca/python3EnvDec/lib/python3.8/site-packages/django/db/utils.py", line 169, in ensure_defaults raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias) django.db.utils.ConnectionDoesNotExist: The connection prueba doesn't exist My settings.py looks like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'decide', 'PASSWORD': 'decide', 'HOST': '127.0.0.1', 'PORT': '5432', }, 'prueba': { 'ENGINE': 'djongo', 'NAME': 'egc-sierrezuela-2', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'HOST': 'mongodb+srv://usuario:password@egc-sierrezuela-2.fxrpl.mongodb.net/egc-sierrezuela-2?retryWrites=true&w=majority' } } } I am using Django=2.0 and djongo=1.2.38 I have tried with many djongo versions and but the errors still arises. Also, upgrading django to the latest version is not possible as I'm using an old project. Any idea? -
Django's static() function to retrieve static file gives no such file -error
I'm doing a project with Django with the following structure: /project /cv /static /configuration configuration.json So a project with one app in it and a config.json file in the static folder. My settings.py (the most important settings for this): INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "cv", ] STATIC_URL = "/static/" BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(BASE_DIR, "cv/static") In my view I use the static() function to retrieve the static file def index(request): file_path = static("configuration/configuration.json") with open(file_path) as f: configuration = json.loads(f.read()) return render(request, "index.html", configuration) But when It keeps giving me the error: No such file or directory: '/static/configuration/configuration.json' I can fix it by explicitly parsing the path string to the index function: "./cv/static/configuration/configuration.json" But how do I do it with the static() function? The static() function uses the static_url variable, but no matter how I adjust it, it keeps giving me a similar error. Anyone an idea what I'm doing wrong here? -
Integration Pycharm, Docker Compose and Django Debbuger getting error: /usr/local/bin/python: can't find '__main__' module. in ''
I'm having a problem using Pycharm to run a Docker container to debug a Django project on MacOs. The Pycharm setup is working fine to run the Django project inside a Docker container. But when I try to do a debugger I'm having the following issue: /usr/local/bin/docker-compose -f /Users/claudius/Studies/Pycharm/test-api/docker-compose.yaml -f /Users/claudius/Library/Caches/JetBrains/PyCharm2021.2/tmp/docker-compose.override.1494.yml up --exit-code-from web --abort-on-container-exit web Docker Compose is now in the Docker CLI, try `docker compose up` mongo is up-to-date postgres is up-to-date Recreating test-api_web_1 ... Attaching to test-api_web_1 Connected to pydev debugger (build 212.4746.96) web_1 | /usr/local/bin/python: can't find '__main__' module in '' test-api_web_1 exited with code 1 Aborting on container exit... ERROR: 1 Process finished with exit code 1 To set up the Pycharm I did: Add a Python interpreter with docker-compose and the container of the web application (Django). Add a Django config for the project. Add a Run/Debugger config. Does someone have any suggestions?