Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a complex constraint on a Django Model?
Dashboards have a team and a user associated with them and have an is_default key. I want to ensure that the is_default key can only be set once as True for each user + company. The user should still be able to create an unlimited amount of is_default=False dashboards. I want to use Djangos constraints for this. However I don't know how to set those up. Here is what I tried so far: constraints = [ models.UniqueConstraint(fields=['user', 'company'], condition=Q( is_default=True), name='unique_primary_dashboard') ] I also tried using the CheckConstraint but I couldn't figure out how to query for the right paramters. At the moment my code apparently restricts nothing. -
How to cascade delete only when last FK relation is deleted in Django?
Given a Many-to-many relation in Django: class Agent: stuff = chars class Protegee: agents = models.ManyToManyField(Agent, related_name="protegees") I'd like a Cascade behaviour on the Protegee, but only if no more agents are related. I.e. as long as a protegee has at least one Agent, it keeps existing. Is there a built-in for that? -
Sudo pip warning inside of docker
I am making simple image of my python django app in docker. But at the end of the building container it throws next warning (I am building it on Ubuntu 20.04): WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead. Why does it throw this warning if I am installing requirements on python inside my image as I understood. I am building my image using sudo docker build -t my_app:1 .. Should I be worried about warning that pip throws, because I know it can break my system?. Here is my dockerfile FROM python:3.8-slim-buster WORKDIR /app COPY requirements.txt requirements.txt RUN pip install -r requirements.txt COPY . . CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] -
How to fix IntelliJ can't run shell or server in terminal?
I had some trouble importing the right module register() in my urls.py, because I had defined a function register() inside a viwes.py in another folder in the same directory. I have attatched a picture: I think it has something to do with the fact that I was working in Programs/mysite/mysite/urls.py and wanted to import from Programs/mysite/register/views.py but Python couldn't find the right module. A pop-up window asked if I wanted to fix the problem by importing someting called registry from Django and I clicked yes because i mistook it for saying 'register'. As you can see in the picture, all files in my register are red now, but I don't know why. I first tried refactoring the folder to 'reguser' instead, and refactored all the usages of 'register' to 'reguser'. I thought that may be the cause of the error, but according to the error-messages I get, I think the problem has something to do with Django.apps.register because I tried running the server to see if it worked, but then I got this error message: The last line in the error-message states " OSError: [WinError 123] Filename, foldername or volumenamesyntax is wrong:'' " Then I tried to open the shell … -
Distance Postgis Django Postgres
i try to develop a estate property app. Now i have app searchcriteria and app estates. searchcriteria.models.py: geopoint = models.PointField(null=True, blank=True) distance = models.PositiveSmallIntegerField(blank=True, default=0, null=True) estates.models.py: geopoint = models.PointField(null=True, blank=True) As you can see searchcriteria and estates have a Pointfield. Now i want from one estate instance search all searchcriteria how match to this estate. Problem is that every searchcirteria have it's own distance entry so circle is different. I now only such Q: Q(geopoint__distance_lte=(searchcriteriageopoint, Distance(km=30))) but this don't work here because different distance per searchcriteria. I found a website: https://blog.programster.org/using-postgis-to-calculate-distance-between-two-points so in as SQL Query i think following is right: SELECT * FROM searchcriteria.Searchcriteria a, estates.Estates b WHERE ST_Distance_Sphere(geometry(a.geopoint), geometry(b.geopint)) < a.distance; How can i write it as Q()? -
Django - Are all relevent models needed when testing the URL of a functional view?
I have several functional views that are passed parameters. I'm trying to write tests to check the url, status, etc. So far I'm starting with just testing the URL name. I have some querysets in the view and it looks from the traceback that I need to define objects for the queries in my setUp urls app_name = 'gradebook' urlpatterns = [ path('updatesinglegrade/<int:assess_pk>/<int:class_pk>/<int:grade_pk>/', views.updatesinglegrade, name='updatesinglegrade'), ] view def updatesinglegrade(request, assess_pk, class_pk, grade_pk): grade = Grade.objects.get(id=grade_pk) gradescale = GradeBookSetup.objects.get(user=request.user) scale_choice = grade_scale_choice(gradescale.scale_mode) form = UpdateGradeForm(gradescale=scale_choice) context = {'form': form} context['grade'] = grade if request.method == 'POST': form = UpdateGradeForm( request.POST, gradescale=scale_choice) if form.is_valid(): cd = form.cleaned_data grade.score = cd['score'] grade.save() return redirect('gradebook:assessdetail', assess_pk, class_pk) else: return render(request, "gradebook/grade_single_form.html", context) else: return render(request, "gradebook/grade_single_form.html", context) test class UpdateSingleGradeTests(TestCase): def setUp(self): self.user = CustomUser.objects.create_user( username='tester', email='tester@email.com', password='tester123' ) login = self.client.login(username='tester', password='tester123') def test_updatesinglegrade_url_name(self): response = self.client.get(reverse('gradebook:updatesinglegrade', kwargs={ 'assess_pk': 1, 'class_pk': 2, 'grade_pk': 3})) self.assertEqual(response.status_code, 200) traceback ====================================================================== ERROR: test_updatesinglegrade_url_name (gradebook.tests.UpdateSingleGradeTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Doug\OneDrive\django\gradebook\gradebook\tests.py", line 102, in test_updatesinglegrade_url_name response = self.client.get(reverse('gradebook:updatesinglegrade', kwargs={ File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\test\client.py", line 742, in get response = super().get(path, data=data, secure=secure, **extra) File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\test\client.py", line 396, in get return self.generic('GET', path, secure=secure, **{ File "C:\Users\Doug\.virtualenvs\gradebook-6RQSg7dk\lib\site-packages\django\test\client.py", line … -
What's the best way to style an email template in Django?
I am trying to style an email template in Django. From researching the best way to do this seems to be to do inline CSS styles. This seems like it would be a tedious process so was wondering if anyone has any better suggestions? I saw another suggestion saying to use django-inlinecss but I can't for the life of me locate the css file when using {% inlinecss "static/css/email.css" %} Path of template: Coronavirus_Dashboard/home/templates/home/newsletter_emails/newsletter_body.html Path to CSS: Coronavirus_Dashboard/static/css/email.css I just keep getting a file not found error, not sure what way I need to specify the location. -
I'm creating a social web using django, I need to create a group model with an group admin who can perform activities such as add and remove members
I'd like that when a group is created then the instance of the profile that creates the group automatically becomes the group admin likewise he/she becomes a group member,couple of basic methods tried returns manytomany relationship errors pointing at add,set functions, how can this be achieved??, I'm using django restframework. Groups model. class Group(models.Model): group_name = models.CharField(max_length=200, blank=True) description = models.TextField( help_text='Describe this group...', max_length=350, blank=True) admin = models.OneToOneField( "profiles.Profile", blank=True, on_delete=models.SET_NULL, null=True, related_name='group_admin') members = models.ManyToManyField( "profiles.Profile", blank=True, related_name='members') posts = models.ForeignKey( "posts.Post", blank=True, on_delete=models.SET_NULL, null=True, related_name='group_posts') created_by = models.ForeignKey( "profiles.Profile", on_delete=models.SET_NULL, null=True, related_name='group_creator') created = models.DateTimeField(auto_now=True) -
how to join a table more than once when a table references different rows of that table
I have a table which can have up to 3 references to another table. here it is in my Django ORM class CreatorCategories(models.Model): name = models.CharField(max_length=100, unique=True) icon = models.CharField(max_length=200, unique=True) class ContentCreatorUsers(models.Model): creatorcategory1 = models.ForeignKey(CreatorCategories, related_name='creatorcategory1', on_delete=models.DO_NOTHING, null=True, blank=True) creatorcategory2 = models.ForeignKey(CreatorCategories, blank=True, related_name='creatorcategory2', null=True, on_delete=models.SET_NULL) creatorcategory3 = models.ForeignKey(CreatorCategories, blank=True, null=True, related_name='creatorcategory3', on_delete=models.SET_NULL) topbannerphotokey = models.CharField(max_length=100, null=True, blank=True) I am running a sql query in a aws lambda (I have not added the select statements that will get the values for a categories name and icon) SELECT id, creatordisplayname, contentcreatordisplaycardurl, creatorurlslug, currentmonitaryactioncount, isverifiedcontentcreator FROM users_contentcreatorusers INNER JOIN users_creatorcategories ON users_contentcreatorusers.creatorcategory1_id= users_creatorcategories.id INNER JOIN users_creatorcategories ON ISNULL(users_contentcreatorusers.creatorcategory2_id, NULL) = ISNULL(users_creatorcategories.id, NULL) INNER JOIN users_creatorcategories ON ISNULL(users_contentcreatorusers.creatorcategory3_id, NULL) = ISNULL(users_creatorcategories.id, NULL) WHERE approvedcreator = true ORDER BY currentmonitaryactioncount DESC LIMIT 12; this sql query keeps giving me the same error: Traceback (most recent call last): File "browsecontentcreatorstest.py", line 115, in <module> lambda_handler() File "browsecontentcreatorstest.py", line 57, in lambda_handler cur.execute(''' psycopg2.errors.DuplicateAlias: table name "users_creatorcategories" specified more than once I need to be able to grab the name and the icon of each of the categories a creator has. I'm not sure how to do this without joins. And the documents I have … -
Add script tag to all django templates
My Django app contains 100+ HTML templates (should've made a web app). I need to add a user feedback widget similar to Usersnap. One way is to add a script tag to all of the 100+ template files and make sure it's added in all future files as well. Is there a way to add the script tag without repeating the code 100+ times? -
Problem with static files in django heroku
I have sam problems this static files in django. I sucsesfull deploy django app to heroku and this site workin https://timon-webchat.herokuapp.com/, but how you can see without any styles or images. But if runing python manage.py runserver local all good and I can see styles, js-codes and images Please tell me what's wrong here is mine setings.py file: """ Django settings for web_chat project. Generated by 'django-admin startproject' using Django 3.1.7. For more information o n this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. from django.urls import reverse_lazy import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+*yv5wtriwzs91yk!gpu27r!p+b1063n26bpjf79+=236yu4%t' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_gravatar', 'app_chat', 'acounts', ] AUTH_USER_MODEL = 'acounts.User' LOGIN_REDIRECT_URL = reverse_lazy("main") LOGOUT_REDIRECT_URL = reverse_lazy("login") MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] MIDDLEWARE_CLASSES = … -
Python Skipping If Statement in Class
I have the following Django class view: class AddOrder(View): product_type = "BarZero Monolithic" template_name = "" def get(self, request): if not request.user.is_authenticated: return redirect("login") context = {} if (self.product_type == "Barzero Monolithic"): form = AddClearChoiceOrderForm(request.POST or None) elif (self.product_type == "AccuFrame 360 PMMA"): form = AddPMMAOrderForm(request.POST or None) elif (self.product_type == "AccuFrame 360 Zirconia"): form = AddZirconiaOrderForm(request.POST or None) if form.is_valid(): fs = form.save(commit=False) fs.clearchoice_center_name = request.user.prosthodontist.prosthodontist fs.email_for_design_approval = request.user.prosthodontist.email_ack fs.product_type = self.product_type fs.save() orders = WebOrder.objects.filter( Q(clearchoice_center_name = fs.clearchoice_center_name), Q(patient_identifier = fs.patient_identifier), Q(barzero_zirconia_options = fs.barzero_zirconia_options), Q(bar_type_options = fs.bar_type_options), Q(arch_type = fs.arch_type), Q(tooth_shade = fs.tooth_shade), Q(cagenix_gingiva_shade = fs.cagenix_gingiva_shade), Q(patient_scheduled_date = fs.patient_scheduled_date), Q(requested_delivery_date = fs.requested_delivery_date), Q(email_for_design_approval = fs.email_for_design_approval), Q(special_instructions = fs.special_instructions) ) order = orders[0] return HttpResponseRedirect(reverse('print_order_i', args=(order.id,))) context['form'] = form return render(request, self.template_name, context) and the following url code: path('addorder/BarZero', AddOrder.as_view(product_type="BarZero Monolithic", template_name="order/add_barzero_order.html"), name="create_barzero_order"), This pushes out the following error through the site debugger: UnboundLocalError at /order/addorder/BarZero local variable 'form' referenced before assignment if form.is_valid(): It seems that the code is skipping over my if statement for some reason, that I can not understand, so please educate me on how to fix this. -
Django: extended user with proxy model to add extra method, how to use the method in template?
I extend the default user model with a proxy model to add an extra method. from django.contrib.auth.models import User class Person(User): class Meta: proxy = True def custom_method(self): pass The main purpose is to use the method in templates. <div>{{ user.custom_method }}</div> But since the user is pointing to the default user model, it has no access to the custom_method. Is there any way to achieve this other than create a subclass of the User model? -
User-specific download file in django
i have an app in django that do some processes and build a file, in one section, i want to show the user that file to download that. (for example, user enter a name in front-end and the app give him a pdf file to download). the file building process is ok and it is in /app_dir/media/app/report/username/file.pdf here is my code, but it does not worked and i faced some problems. can you please help me, where is my problem? and how i can make that user-specefic? each user just can access to his files. views.py (my_main_function): views.py (download function): urls.py: simple testing download.html file: -
django.db.utils.IntegrityError: NOT NULL constraint failed: rango_category.super_cat_id
/*tests.py*/ def create_user(username, password): user = get_user_model().objects.create_user(username=username, password=password) return user #helper function to populat database def create_category(name, super, user): category = Category.objects.get_or_create(name=name)[0] category.super = super category.user = user category.save() return category def create_super_category(title): super = SuperCategories.objects.create(title=title) super.save() return super # The following test is for the save and deleting of # a page from the favorites list class TestFavoritesFeature(TestCase): def setUp(self): self.user = create_user("testUser", "testPassword") self.super = create_super_category('Frameworks') self.cat = create_category('python', self.super, self.user) /* Models */ class SuperCategories(models.Model): title = models.CharField(max_length=maxLength128) def __str__(self): return self.title class Category(models.Model): super_cat = models.ForeignKey(SuperCategories, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=maxLength128, unique=True) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name Both the object.create and object.get_or_create give an error for NOT NULL field. Above is the code , 2 models and both throw an error on only the id field that we do not even populate. It is the function's job to assign a unique id to it. The above is code from tests.py file. I am trying to populate DB for unit testing . In the actual code, these objects.get_or_create or objects.create do not give errors but are rather … -
How can I submit multiple forms using Django and JavaScript?
I'm working on an app that displays a form on the index page, into which you can enter information to eventually calculate a gross total and output other details based on the form inputs. My form inherits from form.Forms. A button, "Add row", creates as many copies of this row as needed. Each form contains a form with the ID "calc-form". My problem is that only one form is included in the POST method. I would like to process all forms with one click. How can I include all additional forms in the POST method when I click "Calculate"? index.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} {% load static %} <script type="text/javascript" src="{% static 'app.js' %}"></script> <table id="table-id"> <tr id='table-row'> <form id="calc-form" action="{% url 'result' %}" method="post"> {% csrf_token %} {% for field in form %} <td>{{ field|as_crispy_field }}</td> {% endfor %} </form> </tr> </table> <br> <input type="submit" value="Calculate" form="calc-form"> <button type="button" id="add-row-btn" onclick="addRow()">Add row</button> <button type="button" id="delete-row-btn" onclick="deleteRow()">Delete last row</button> {% endblock content %} views.py from django.shortcuts import render from .forms import TariffCalcForm def index(request): form = TariffCalcForm context = {'form': form} return render(request, 'clickapp/index.html', context) def result(request): context = {} if request.method … -
Not able to host the python application in docker
I'm trying to host the sample application in docker. But not able to host. run the application. I believe it should host in http://127.0.0.1:8001 I have exposed the port 8001 docker file FROM python:3.9-alpine3.13 EXPOSE 8001 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 COPY requirements.txt . RUN python -m pip install -r requirements.txt WORKDIR /app COPY . /app RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app USER appuser CMD ["gunicorn", "--bind", "0.0.0.0:8001", "pythonPath.to.wsgi"] docker-compose.yml version: '3.4' services: vscodedjangodocker: image: vscodedjangodocker build: context: . dockerfile: ./Dockerfile ports: - 8001:8001 -
Is it secure for Django to store the CSRF token in a cookie?
I'm using React and Django for my web application. As far as I know, Django uses a double submit pattern, where the CSRF token in the cookie and header/body are compared server side. I use the following code to extract the CSRF token from document.cookie as specified by Django docs: export function getToken() { let cookieValue = null; const name = "csrftoken"; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent( cookie.substring(name.length + 1) ); break; } } } return cookieValue; } I then use it like so: axios .post("/api/auth/login", { username: username, password: password, }, { withCredentials: true, headers: { "X-CSRFToken": getToken(), } } So my question is, I've heard that an attacker can't access a user's cookies and thus can't extract the CSRF token to place in the request header/body. But why can't the attacker execute a script running the getToken function and place the result in a header like I did? (Say we ignore CORS for the sake of argument) Example: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" … -
Getting False value for a key in self.data even when it is not present in the request
I have 2 radio buttons in the UI, one for setting a variable (ng-model) say selected as true (ng-value=true) and other one for setting it as false (ng-value=false). Now, when none of them is selected it results in the variable selected being absent from the outgoing request (as expected). However, when that is dealt with Django Forms, the self.data dictionary in the clean() method gives False on accessing self.data.get('selected') / self.data['selected'] why is that so? Shouldn't it be None or at least give a key-error when it was not even present in the actual request? Note that the variable 'selected' is actually a field in a Django Model with default=False, is that thing responsible for this behaviour? How can I circumvent this situation considering that altering the Django Model field isn't an option? -
Why images on Cloudinary doesn't show up? I've tried many times but nothing
I have a profile's model and a post model. When debug mode is set to False, images don't appear. Here is my settings.py from pathlib import Path import os import dj_database_url import cloudinary_storage BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY', '...') DEBUG = os.environ.get('DEBUG', False) ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django.contrib.sitemaps', 'cloudinary_storage', 'taggit', 'tinymce', 'ckeditor', 'sweetify', 'hitcount', 'storages', 'notifications', 'django_resized', 'django_countries', 'post', 'website', 'comment', 'announce', 'superadmin', 'commissions', 'sitemanagement', 'profil.apps.ProfilConfig', ] CLOUDINARY_STORAGE = { 'CLOUD_NAME': os.environ.get('CLOUD_NAME', 'name'), 'API_KEY' : os.environ.get('API_KEY', 'key'), 'API_SECRET' : os.environ.get('API_SECRET', 'secret'), } DEFAULT_FILE_STORAGE = os.environ.get('DEFAULT_FILE_STORAGE', 'cloudinary_storage.storage.MediaCloudinaryStorage') MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'club.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'club.wsgi.application' # Database DATABASES = { 'default': { 'ENGINE': os.environ.get('ENGINE', 'django.db.backends.postgresql'), 'NAME': os.environ.get('NAME', 'name'), 'USER': os.environ.get('USER', 'user'), 'HOST': os.environ.get('HOST', 'host'), 'PASSWORD': os.environ.get('PASSWORD', 'password'), 'PORT': os.environ.get('PORT', 'port'), } } db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) """ # EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_LOCALTIME = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER', 'email_address') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_USER', 'email_password') AUTH_PASSWORD_VALIDATORS = [ … -
Cannot connect django container to postgres on a linux host machine
After going through all of the Stackoverflow threads on this topic, I still could not solve the problem. This happens only on my Fedora laptop, on my Macbook, the docker containers work perfectly fine. My docker-compose.yml file is very standard: version: "3.8" services: app: container_name: data-management restart: always build: ./ ports: - '3000:3000' links: - 'postgresdb' volumes: - ./:/usr/local/share/src/app env_file: - .dev.env postgresdb: container_name: be-postgres restart: always image: postgres:12.7-alpine ports: - '5432:5432' volumes: - postgres-db:/var/lib/postgresql/data env_file: - .dev.env volumes: postgres-db: As you can see the environment variables are read in both containers from a file: POSTGRES_PASSWORD=devpassword123 POSTGRES_USER=devuser POSTGRES_SERVICE=postgresdb POSTGRES_PORT=5432 These env variables are also used in the settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ['POSTGRES_SERVICE'], 'NAME': os.environ['POSTGRES_USER'], 'PORT': os.environ['POSTGRES_PORT'], 'USER': os.environ['POSTGRES_USER'], 'PASSWORD': os.environ['POSTGRES_PASSWORD'], } } The problem that I am having is that the django application cannot connect to the postgresDB: django.db.utils.OperationalError: could not connect to server: Host is unreachable Is the server running on host "postgresdb" (172.xx.x.x) and accepting TCP/IP connections on port 5432? I also checked if the port in the postgres container is opened and it is: / # netstat -tuplen Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program … -
SQL - How to split values in field with commas in multiple rows
I have a field in a MySQL table with '3,4,7,16' in it. These values are store in another table id - value 1 - name1 2 - name2 ... 16 - name16 I would like to get then in 4 rows 3 4 7 16 I have seen many answer but they need temporary table, function, loop or procedure. I am using Django ORM and can not do that in the query. Can you help to solve this issue ? -
Can't load django-sortedm2m
I downloaded the Django package django-sortedm2m and I added it to settings.py as sortedm2m but when I tried to load the package in models.py with: from sortedm2m.fields import SortedManyToManyField And Django didn't recognize it. Is it possible that the package is deprecated? I'm using Django version 3.1.7 and Python 3.8.10. If this can't be solved, is there any similar package? -
How to create serializer with nested data DRF?
I have seen many tutorials about nested serializer, but unfortunately I can`t solve this task. Please, give me some tips. I need to create this JSON { "external_id": "11", "details": [ { "amount": 7, "price": "12.00", "product": { "name": "Car" } } ] } My models consist the next relative: from django.db import models class Order(models.Model): NEW = 'new' ACCEPTED = 'accepted' FAILED = 'failed' order_status = [ (NEW, 'new'), (ACCEPTED, 'accepted'), (FAILED, 'failed'), ] status = models.CharField(max_length=12, choices=order_status, default='new', blank=False) created_at = models.DateTimeField(auto_now_add=True) external_id = models.CharField(max_length=128) def __str__(self): return f'Order № {self.external_id}' class Product(models.Model): name = models.CharField(max_length=64) def __str__(self): return self.name class OrderDetail(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='details', null=True, blank=True) amount = models.IntegerField(null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product', null=True) price = models.DecimalField(decimal_places=2, max_digits=6, null=True, blank=True) def __str__(self): return f'Detail for {self.order}, detail for product {self.product}' My view class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class OrderViewSet(ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer pagination_class = ContentRangeHeaderPagination class OrderDetailViewSet(ModelViewSet): queryset = OrderDetail.objects.all() serializer_class = OrderDetailSerializer My serializer class OrderDetailSerializer(serializers.ModelSerializer): class Meta: model = OrderDetail fields = ['id', 'amount', 'price'] depth = 1 class ProductSerializer(serializers.ModelSerializer): product = OrderDetailSerializer(many=True) class Meta: model = Product fields = ['id', 'name', 'product'] class OrderSerializer(serializers.ModelSerializer): … -
netlify build failure: npm ERR! path /opt/build/repo/package.json
I have a django 1.10 app which I have deployed to netlify but is failing to build. I'm using the django distill app to generate the static files. and I have pushed these to https://github.com/kc1/static1 . The netlify build log has; 1:12:57 PM: $ npm run-script build 1:12:57 PM: npm ERR! code ENOENT 1:12:57 PM: npm ERR! syscall open 1:12:57 PM: npm ERR! path /opt/build/repo/package.json 1:12:57 PM: npm ERR! errno -2 1:12:57 PM: npm ERR! enoent ENOENT: no such file or directory, open '/opt/build/repo/package.json' 1:12:57 PM: npm ERR! enoent This is related to npm not being able to find a file. 1:12:57 PM: npm ERR! enoent 1:12:57 PM: npm ERR! A complete log of this run can be found in: 1:12:57 PM: npm ERR! /opt/buildhome/.npm/_logs/2021-08-05T17_12_57_910Z-debug.log 1:12:57 PM: 1:12:57 PM: ──────────────────────────────────────────────────────────────── 1:12:57 PM: "build.command" failed 1:12:57 PM: ──────────────────────────────────────────────────────────────── 1:12:57 PM: 1:12:57 PM: Error message 1:12:57 PM: Command failed with exit code 254: npm run-script build As you can see in the repo I don't have a package.json ( this came from python ). Do I need to create one? How do I get this working?