Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Browser loads an empy css
css located in my_blog/my_blog/blog/static/blog/style.css manage.py in my_blog/my_blog head of html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'blog/style.css' %}"> <title>{% block title%} My blog {% endblock %}</title> </head> I'm using pycharm pro. Browser successfully load css file, but it's empty. Why this is happenning? -
How Django async view handle simultaneous requests
I test 2 views in Django 3.2: def sync_view(request): return HttpResponse("Hello, sync Django!") async def async_view(request): await asyncio.sleep(10) return HttpResponse("Hello, async Django!") start uvicorn as uvicorn myapp.asgi:application First request to async_view, right after to sync_view. My expectation that sync_view will response immediately, however it is handled only after 10 seconds. What is wrong? Why requests are not handled simultaneously? -
How to pass pk argument within class based view to queryset in Django
I have the following Django urls/views and Models: Models ORDER_COLUMN_CHOICES = Choices( ('0', 'id'), ('1', 'code'), ('2', 'code_type'), ('3', 'created'), ('4', 'updated'), ('5', 'valid'), ) class Identifier(TimeStampMixin, models.Model): code_type = models.CharField(max_length=10, null=True) code = models.CharField(max_length=12) account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) actflag = models.CharField(max_length=1, blank=True) valid = models.BooleanField(default=False) def __str__(self): return self.code class Meta: db_table = "portfolio_identifier" def query_identifier_by_args(**kwargs): draw = int(kwargs.get('draw', None)[0]) length = int(kwargs.get('length', None)[0]) start = int(kwargs.get('start', None)[0]) search_value = kwargs.get('search[value]', None)[0] order_column = kwargs.get('order[0][column]', None)[0] order = kwargs.get('order[0][dir]', None)[0] order_column = ORDER_COLUMN_CHOICES[order_column] # django orm '-' -> desc if order == 'desc': order_column = '-' + order_column queryset = Identifier.objects.all() total = queryset.count() if search_value: queryset = queryset.filter(Q(id__icontains=search_value) | Q(code__icontains=search_value) | Q(code_type__icontains=search_value) | Q(created__icontains=search_value) | Q(updated__icontains=search_value) | Q(valid__icontains=search_value)) count = queryset.count() queryset = queryset.order_by(order_column)[start:start + length] return { 'items': queryset, 'count': count, 'total': total, 'draw': draw } URLS from . import views from rest_framework.routers import DefaultRouter from apps.portfolio.views import IdentifierViewSet router = DefaultRouter() router.register(r'portfolio', IdentifierViewSet) urlpatterns = [ path('portfolios/', views.portfolios, name="portfolios"), path('portfolio/<str:pk>/', views.portfolio, name="portfolio"), path('api/', include(router.urls)), ] Views def portfolio(request, pk): portfolio = Account.objects.get(id=pk) identifiers = Identifier.objects.filter(account=pk) context = {"portfolio": portfolio, "identifiers": identifiers} return render(request, 'portfolio.html', context) class IdentifierViewSet(viewsets.ModelViewSet): queryset = Identifier.objects.all() serializer_class = IdentifierSerializer authentication_classes = … -
Django: Code only executing on watcher reload?
I'm working with Django and I have code that I'm attempting to execute on page load, but it isn't executing. All I've set it to do is print something and it only prints when Django's watcher sees a code change (and it's immediate on watcher reload, after that it won't print at all)... Here's my codebase: https://github.com/varlenthegray/wcadmin/blob/master/qb/views.py#L590 Here's the view: def update_db_from_changes(request): # Get all records that do not equal 12 for service interval all_non_standard_invoices = Invoice.objects.filter(~Q(service_interval=12)).select_related('job_site') print("I don't get it, this should work.") return HttpResponse("Did nothing!") Watcher results: System check identified no issues (0 silenced). June 09, 2022 - 16:01:06 Django version 4.0.5, using settings 'wcadmin.environment.production' Starting development server at http://127.0.0.1:3000/ Quit the server with CONTROL-C. I don't get it, this should work. Watching for file changes with StatReloader Page refresh results: Watching for file changes with StatReloader [09/Jun/2022 16:06:50] "GET /qb/update_changes/ HTTP/1.1" 200 12 Page results: Did nothing! Any thoughts on how to best approach debugging this issue? -
Access domain (and port) URL in settings.py file while in localhost development
How do you dynamically access the domain name URL in the settings.py file of Django? (ie "http://localhost:8000") I am trying to overwrite a package CDN while the internet is unavailable during development, and want to point to the local file in the static files directory. While os.path.join(BASE_DIR, "path/to/local.file") should work, it is context-dependent as to which app/url (ie "http://localhost:8000/app/static/css/bootstrap.min.css "), and not just the main domain with the static file location appended to the starting server with ./manage.py runserver 0:8000 (ie " http://localhost:8000/static/css/bootstrap.min.css"). Notes: Because this is in the settings.py, I can't load any apps or reverse because of the error *** django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I am not in a template, so I can't use the static url statically defining it won't allow for different port loadings when starting via ./manage.py runserver 0:8000 Basically in the settings.py file: # If in local dev if "RDS_DB_NAME" not in os.environ: # the setting for the package I am pointing to a local version BOOTSTRAP5 = { "css_url": { ### dynamically get domain here ### # "href": os.path.join(LOCAL_DIR, "static/css/bootstrap.min.css"), "href": "static/css/bootstrap.min.css", } -
Django model form won't save/validate
I am new to Django and I have a comments form on a listing page of a marketplace site I am working on. When trying to enter a comment they don't save. I assume the is_valid() is not returning True so the saving never occurs, but I don't see why it wouldn't be valid. I thought that function primarily checked all fields were filled with valid data. As I said I'm new to Django so any advice would be appreciated. The Else redirect is temporary until I get it working correctly. Views.py @login_required def comment(request, listing): listing = AuctionListings.objects.get(name=listing) form = NewCommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.listing = listing comment.save() return HttpResponseRedirect(reverse("listing", args=[listing.name])) else: return HttpResponseRedirect(reverse("listing", args=[listing.name])) models.py class Comments(models.Model): listing = models.ForeignKey(AuctionListings, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=255, validators=[MinLengthValidator(1)]) date = models.DateTimeField(auto_now_add=True) forms.py class NewCommentForm(forms.ModelForm): class Meta: model = Comments fields = [ 'comment' ] widgets = { 'comment': forms.Textarea(attrs={ 'placeholder': 'Enter your comment (255 char. max)', }) } -
Reliably accessing request.user in Django custom LoginView
I have a custom LoginView and I'd like to take the shopping cart of a LazyUser pre-login and consolidate it with the cart of the user after login: class LoginView(FormView): ... def form_valid(self, form): request_user = self.request.user user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password']) if user is not None: login(self.request, user) try: user.consolidate_carts(request_user) except Exception as e: print('error in consolidate_carts: ', e) return HttpResponseRedirect(self.success_url) else: return render(self.request, 'users/login.html') This seems to work some of the time, but it is unreliable - I believe that is because I am simply referencing self.request.user and it is a SimpleLazyObject. What would be the pythonic/optimal way to store the user pre-login? -
Can not deserialize instance of io.vavr.collection.Seq out of VALUE_STRING
I was trying to build a python request module passing API tokens, however I am running into below issue every time. Sharing my entire code : import requests import json def bitbucketFunction(): variables = {"test":"1234"} callBitBucketAPI(variables) def callBitBucketAPI(variables): try: headers = { 'Content-Type': 'application/json' } url = "https:xyz/pipelines/" data = { "target": { "type": "pipeline_ref_target", "ref_type": "branch", "ref_name": "master", "selector": { "type": "custom", "pattern": "create-aws-account" } },"variables":json.dumps(variables, indent=2)} response = requests.request("POST",url, auth=('token-key', 'token-value'), data=json.dumps(data),headers=headers) print(response.text) except Exception as e: print("Exception occured in callBitBucketAPI method: ", e) bitbucketFunction() Error: {"error": {"message": "An invalid field was found in the JSON payload.", "fields": ["variables"], "detail": "Can not deserialize instance of io.vavr.collection.Seq out of VALUE_STRING token\n at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 167] (through reference chain: com.atlassian.pipelines.rest.model.v1.pipeline.ImmutablePipelineModel$Builder[\"variables\"])", "data": {"key": "rest-service.request.invalid-json"}}} -
Django: I need to supersede a particular Python module in a no-longer-maintained package
Well, I think that the "Pinax" package is no longer maintained ... Anyway, it refers to a now-deprecated django.utils.tzinfo package. I need to make a one-line change to one source module, and then cause that version of the package to be loaded instead of the one in the module directory. Is there a generic way in Django to do that sort of thing? (I know that some packages such as the Machina forum software can do this.) -
djago-gis: Can't serialize dictionary with GeoFeatureModelSerializer: KeyError: 'id', even with .is_valid=True and excluding id
I'm trying to prototype a view receiving some geojson. I'm using a jupyter notebook, with (https://gist.github.com/codingforentrepreneurs/76e570d759f83d690bf36a8a8fa4cfbe)[the init_django script in this link). Trying to serialize this geojson (that has been transformed into a dict) {'id': '0', 'type': 'Feature', 'properties': {'area': 0.74, 'gloc1': sensitive, 'gloc2': sensitive, 'gloc3': sensitive, 'gloc4': sensitive, 'gloc5': sensitive}, 'geometry': {'type': 'MultiPolygon', 'coordinates': [some_coordinates]}} Is giving me problems with some id field. Here is the model serializer using the rest_framework_gis library. class Local(GeoFeatureModelSerializer): # cliente = PrimaryKeyRelatedField(queryset=ClienteModel.objects.all()) class Meta: model = LocalModel fields = "__all__" geo_field = "geom" Here is the model i'm using from django.contrib.gis.db.models import Model class Local(Model): status_choice = TextChoices('status', 'ATIVO INATIVO PONTUAL') gloc1 = TextField(null=False) gloc2 = TextField(null=False) gloc3 = TextField(null=False) gloc4 = TextField(null=False) gloc5 = TextField(null=False) latitude = FloatField(null=True, blank=True) longitude = FloatField(null=True, blank=True) altimetria = FloatField(null=True, blank=True) capacidade_retencao_agua = FloatField(null=True, blank=True) coef_textura_agua_solo = FloatField(null=True, blank=True) coef_potencia_agua_solo = FloatField(null=True, blank=True) sk1m = FloatField(null=True, blank=True, default=0) sk2m = FloatField(null=True, blank=True, default=1) smaw = FloatField(null=True, blank=True, default=0) sfer = FloatField(null=True, blank=True, default=1) profundidade_efetiva_maxima = FloatField(null=True, blank=True) cti = FloatField(null=True, blank=True) slo = FloatField(null=True, blank=True) geom = GeometryField(srid=4326, null=False) data_criacao = DateField(auto_now=True) data_atualizacao = DateField(auto_now_add=True) #null-False here cena_s2 = TextField(null=True, blank=True) area = FloatField(null=True, blank=True) grupo = … -
CKEditor RichTextUploadingWidget preventing page scroll
I'm using a fullpage.js frontend with a Django backend. In the Django models, I defined some fields with the RichTextUploadingField. The fullPage.js page does not work with scrolloverflow if I do this. I cannot scroll down to the next page. If I change the RichTextUploadingField back to a normal TextField everything works fine. Any ideas? -
Django/Apache authentication successful but does not return @loginrequired view instead redirects to index
I have a Django application with token-based auth. I served this app on AWS before without problem. Now I want to serve it via Apache2 but it fails to open a 'login required' page after successful login. Here is my code: views.py def index(request): print('Access to page "home"') return render(request, 'index.html') @login_required(login_url='/') def memory(request): print('Access to page "memory"') return render(request, 'memory.html') user_api.py @api_view(["POST"]) @permission_classes((AllowAny,)) @csrf_exempt def doLogin(request): body_unicode = request.body.decode('utf-8') user = json.loads(body_unicode) dbUser = User.objects.filter(username=user['username']) if not dbUser: return HttpResponse(status=404) authenticatedUser = authenticate(username=user['username'], password=user['password']) if authenticatedUser: login(request, authenticatedUser) token, _ = Token.objects.get_or_create(user=authenticatedUser) return Response({'token': token.key}, status=HTTP_200_OK) else: return Response(status=401) LoginModal.vue login() { if (!this.user.username || this.user.username == '' || !this.user.password || this.user.password == '') { this.warningText = 'All fields must be filled.' return } axios.post(this.backendAddress + 'api/user/login', this.user) .then((response) => { sessionStorage.setItem('token', response.data.token) document.cookie = 'apitoken=' + response.data.token window.location.href = 'memory' }, function (err) { printError(err) }) } After I entered my username/password and hit login, it makes the request and redirects to index with ?next=memory, meaning that it doesn't recognized user as logged in. After successfull login I store my token as 'apitoken' parameter in the cookie. What's wrong with my method? Thanks. -
django form not showing in template to add data
the goal of my code is to make a school management system where the admin can log in and add teachers to their respective classes that they are leading and be able to add students to their respective classes and then take the attendance of those students present on any given day. however, I am having an issue where the form to add the student to the class isn't rendering when I click on the add student button. I have been searching but can't seem to find the error in my code, I am new to Django so any help will be appreciated. the closest I got was to make the modal show up but the fields to select the student from to add to the class wasn't showing models class Teacher(models.Model): first_name = models.CharField(max_length=60, blank=False, null=False) last_name = models.CharField(max_length=80, blank=False, null=False) address = models.CharField(max_length=120, blank=True, null=True) contact = models.CharField(max_length=10, blank=True, null=True) email = models.EmailField(blank=True, null=True) birth = models.CharField(max_length=20, blank=True, null=True) gender = models.CharField(max_length=100, choices=[('Male', 'Male'), ('Female', 'Female')], blank=True, null=True) comment = models.TextField(max_length=10000, blank=True, null=True) def __str__(self): return f"{self.first_name + ' ' + self.last_name}" class Student(models.Model): student_code = models.CharField(max_length=250, blank=True, null=True) first_name = models.CharField(max_length=20, blank=False, null=False) last_name = models.CharField(max_length=20, blank=False, … -
Django way to make a chat app without django-channels
how can I make a chat app without django-channels. I want to do it with something like socketio. I found in Google a module named django-socketio. Should I do it with this? Please write me the code to do this or write a link of a tutorial. Should I do it with something different? Thanks. -
Can't connect with my django rest framework API with axios in react native
I'm developing an application with React Native and I can't connect to my own API. I made a database with django rest framework and I'm trying to connect to it with axios. I'm receiving an error with "Network Error" message with the name "AxiosError". Here is the error (with error.toJSON()): Object { "code": "ERR_NETWORK", "columnNumber": undefined, "config": Object { "adapter": [Function xhrAdapter], "data": undefined, "env": Object { "FormData": null, }, "headers": Object { "Accept": "application/json, text/plain, /", }, "maxBodyLength": -1, "maxContentLength": -1, "method": "get", "timeout": 0, "transformRequest": Array [ [Function transformRequest], ], "transformResponse": Array [ [Function transformResponse], ], "transitional": Object { "clarifyTimeoutError": false, "forcedJSONParsing": true, "silentJSONParsing": true, }, "url": "http://127.0.0.1:8000/api/usuario", "validateStatus": [Function validateStatus], "withCredentials": false, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", }, "description": undefined, "fileName": undefined, "lineNumber": undefined, "message": "Network Error", "name": "AxiosError", "number": undefined, "stack": undefined, "status": null, } Currently I'm doing it without authentification needed because i thought I should have less errores (tried it also with authentification earlier a lot and same error). This is my axios function: try { const axios = require('axios'); const students = await axios.get('http://127.0.0.1:8000/api/usuario', {withCredentials: false}); //const students = await axios.get('https://jsonplaceholder.typicode.com/todos/1'); setPrueba(JSON.stringify(students.data)); The line commented is a API that gives a placeholder json, and … -
mod_wsgi: "No module named 'django'"
Maybe some needed context: I installed python3.9 into a directory /opt/python39/. I compiled mod_wsgi with this version of python and was able to conduct a test to make sure that it was working correctly. I am not using a virtual environment. I am trying to move my django project to production, so naturally, I am following the django docs. When I use the default file configurations at the very beginning, i.e.: WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py WSGIPythonHome /opt/python39/bin/python3.9 WSGIPythonPath /path/to/mysite.com <Directory /path/to/mysite.com/mysite> <Files wsgi.py> Require all granted </Files> </Directory> It works (for the most part - there are resources missing on the page, but thats for another SO post) like a charm. So I continue through the docs (which is now telling me that I should move it to "Daemon mode"): “Daemon mode” is the recommended mode for running mod_wsgi (on non-Windows platforms). To create the required daemon process group and delegate the Django instance to run in it, you will need to add appropriate WSGIDaemonProcess and WSGIProcessGroup directives. A further change required to the above configuration if you use daemon mode is that you can’t use WSGIPythonPath; instead you should use the python-path option to WSGIDaemonProcess, for example: So I change … -
How can I get Django to send error emails on status codes above 500?
I have migrated an old codebase to a new server and am now running Django 4.0.5. I can send emails from the shell as follows: from django.core.mail import mail_admins mail_admins(subject='test', message='test') But I don't receive any emails on 500 or higher errors. My settings are: DEBUG = env('DEBUG') ADMINS = [('My Name', 'me@provider.com'),] MANAGERS = ADMINS ADMIN_EMAIL = ['me@provider.com',] DEFAULT_FROM_EMAIL = 'admin@provider.com' SERVER_EMAIL = 'admin@provider.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'admin@provider.com' EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_USE_TLS = True And i have tried adding: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' But they are still not sent. I am using django-environ, but debug is set to false. Any ideas what the problem could be? -
Django celery error while adding tasks to RabbitMQ message queue : AttributeError: 'ChannelPromise' object has no attribute '__value__'
I have setup celery, rabbitmq and django web server on digitalocean. RabbitMQ runs on another server where my Django app is not running. When I am trying to add the tasks to the queue using delay I am getting an error AttributeError: 'ChannelPromise' object has no attribute 'value' From django shell I am adding the task to my message queue. python3 manage.py shell Python 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from app1.tasks import add >>> add.delay(5, 6) But getting error Traceback (most recent call last): File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/utils/functional.py", line 30, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors yield File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/connection.py", line 433, in _ensure_connection return retry_over_time( File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/utils/functional.py", line 312, in retry_over_time return fun(*args, **kwargs) File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/connection.py", line 877, in _connection_factory self._connection = self._establish_connection() File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/connection.py", line 812, in _establish_connection conn = self.transport.establish_connection() File "/etc/myprojectenv/lib/python3.8/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection conn.connect() File "/etc/myprojectenv/lib/python3.8/site-packages/amqp/connection.py", line 323, in connect self.transport.connect() File "/etc/myprojectenv/lib/python3.8/site-packages/amqp/transport.py", line 129, in connect self._connect(self.host, self.port, self.connect_timeout) File "/etc/myprojectenv/lib/python3.8/site-packages/amqp/transport.py", line 184, in _connect … -
Django: create many-to-Many relationship without creating intermediary table
I have a set of tables that Ive turned into django models. The tables weren't architected very well and i can't change them, and it is causing problems for this one many to many relationship I'm trying to set up in my code. Models class Owner(models.Model): owner_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, unique=True) # Field name made lowercase. email = models.TextField(max_length=200, unique=True) is_active = models.BooleanField( blank=True, null=True) # Field name made lowercase. owned_apps_whistic = models.ManyToManyField("Applications", through="ApplicationOwnerXRef", related_name="owners_whistic") #owned_apps_group = models.ManyToManyField("Applications", through="BusinessUnitOwnerXref", related_name="owners_group") class Applications(models.Model): application_id = models.UUIDField(primary_key=True) url = models.TextField(blank=True, null=True) name = models.TextField(blank=True, null=True) service = models.TextField(blank=True, null=True) status = models.TextField(blank=True, null=True) created_date = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) business_unit_name = models.TextField(blank=True, null=True) class BusinessUnitOwnerXref(models.Model): id = models.AutoField(primary_key=True) owner_uuid = models.ForeignKey(ApplicationOwner, models.DO_NOTHING, to_field="owner_uuid", db_column = "owner_uuid") business_unit_name = models.TextField(max_length=100, null=True) Owners can own applications by owning the group that owns the application, indicated in the BusinessUnitOwnerXref table. The Application table and the BusinessUnitOwnerXref both have the business_unit_name column , and can be directly joined I cant use a foreign key because the BusinessUnitOwnerXref.business_unit_name column isn't unique. TLDR, Is there a way to create the many-to-many relationship between Applications and Owners, through BusinessUnitOwnerXref, without altering the existing tables or letting django … -
How to install python packages on shared host
When I upload my Django app, I have problem when I setup the python app configuration files. After adding requirements.txt gives me an error these libraries are not accepted: matplotlib==3.5.1 pandas==1.3.5 Pillow==9.0.0 psycopg2==2.9.1 scipy==1.7.3 seaborn==0.11.2 Is there a solution? -
"Bot domain invalid" error in web telegram login. Django
When integrating the login via telegram for Django, I received the following error (despite the fact that all actions were done correctly) Bot domain invalid error I've been tinkering with this for a couple of days and just want to share a solution. The solution is simple and pretty funny. Just remove "django.middleware.security.SecurityMiddleware" from MIDDLEWARE -
getting dynamic data from views to javascript
Just like we can set a context variable for the default users in a django template, var user = "{{request.user}}" How do I do the same thing for a custom Model? views def test(request): news = News.objects.all() context = {"news ": news} template <script> var text = "{{request.news}}"; </script> -
Is it possible to take in input from django, and output that to a word document using python docx
I want to take in user input through text boxes on websites created with Django. After gathering the user input I want to automatically generate a word document with the inputs, and output a word document. Is this possible? -
django error : 'the current database router prevents this relation.'
I have 2 models(customer, order) in 2 different sqlite3 databases(custdb and orddb) apart from the default database. Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'custdb': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'custdb.sqlite3', }, 'orddb': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'orddb.sqlite3', } } DATABASE_ROUTERS = ['customer.router.custrouter', 'order.router.ordrouter'] Under 'customer' App, in the models.py, below customer model class is defined(only class definition shown here) class customer(models.Model): name = models.CharField(max_length=50) phone = models.IntegerField() Under order App, in the models.py, below order model is defined(only class definition shown here) class order(models.Model): ordername = models.CharField(max_length=50) customer = models.ForeignKey(cust, default=None, null=True, on_delete = models.SET_NULL) Under 'customer' App, in the router.py, I have defined one router class class custrouter: route_app_labels = {'customer'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'custdb' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'custdb' return None def allow_relations(self, obj1, obj2, **hints): if ( obj1.meta.app_label in self.route_app_labels or obj2.meta.app_label in self.route_app_labels ): return True return True def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'custdb' return None Under 'order' App, in the router.py, I have defined another router class class ordrouter: route_app_labels = {'order', 'customer'} def … -
Django service only works when the image is deleted and pulled again (in Swarm)
I have a swarm cluster with 2 workers and one manager. I built a Django image, pushed it to Docker Hub. I make migrations before pushing the image so it contains them. I pull the image for it to be used for the Swarm services, using docker-compose, I deploy the stack, everything works. But if I remove the stack and try to start it again from the old image (which should be immutable) i get psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known. If I delete the image and just run the stack again (so basically I get the same image from Docker Hub) the service is deployed without any errors. So i cant delete the stack and use the same image to deploy it again.. My compose is: version: "3.3" services: web: image: x command: > bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" env_file: - .env.dev volumes: - migrations-volume:/stack_name/api/migrations/ deploy: replicas: 3 restart_policy: condition: on-failure networks: - web_network - data_network secrets: - firebase_secret - google_cloud_secret healthcheck: test: wget --tries=1 --spider http://localhost:8000/app/ || exit 1 interval: 180s retries: 5 timeout: 10s db: image: postgres:11 command: "-c logging_collector=on" volumes: - database:/var/lib/postgresql/database/ env_file: …