Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test nested Serializers in Django Rest?
I have a ToDo App Django project, and so there are Task and TaskList models which are linked with a ManyToMany relation. Inside my TaskSerializer, I have defined a nested TaskListSerializer which handles the reverse relation of a task's tasklists. Everything is going well in real world, and the serialization and deserialization is ok. This is what you should put request when updating a task (as json): { "title": "hello", "tasklists": [ {"pk": "b84d3375-0e09-4dd1-9809-f92d29d6aa36"}, {"pk": "b84d3375-0e09-4dd1-9809-f92d29d6aa36"} ] } But inside the Tests, I want to test this serializer and, when I'm sending the put request the tasklists field is not sent to the view! This is the test request: path = self.task.get_absolute_api_url() data = { "title": "hello", "tasklists": [ {"pk": "b84d3375-0e09-4dd1-9809-f92d29d6aa36"}, {"pk": "b84d3375-0e09-4dd1-9809-f92d29d6aa36"} ] } self.client.put(path, data) But there is no tasklists field inside the validated_data and initial_data of view.(the title field is sent and validated) I guess that the Renderer and json_encoder have the problem with this type of data. so how should the correct request data be inside a nested serializer test? In General, How to test a Nested Serializer! -
How to handle forward slash in API call
I know this goes against all of the rules, but I have a database that has a primary key in the format of /. Ex. 12345/A. I'm using Django Rest Framework and can't seem to make the API call to retrieve this record. The Django admin changes this to 12345_2FA in the URL, but this doesn't work for the API call. Thanks! -
Django Password Reset Form Not Showing When Using DRF, Works from Website
I'm facing an issue with my Django application involving the password reset functionality. When the password reset link is sent via the standard Django website flow, everything works as expected: the user receives an email with a link, and upon clicking it, they are taken to a page with a form to reset their password. However, when the reset link is sent through a Django Rest Framework (DRF) API (triggered from a Flutter app), the user still receives the email with a link, but the page that opens does not show the password reset form. The rest of the HTML content on the page renders correctly, but the form itself is missing. Here's the relevant part of my CustomPasswordResetConfirmView in Django: class CustomPasswordResetConfirmView(PasswordResetConfirmView): form_class = SetPasswordForm success_url = reverse_lazy('users:password_reset_complete') template_name = 'users/password_reset_confirm.html' @method_decorator(sensitive_post_parameters('new_password1', 'new_password2')) @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.form_class(user=self.request.user) return context And the template users/password_reset_confirm.html is as follows: <main class="mt-5" > <div class="container dark-grey-text mt-5"> <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Reset Password</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Reset Password</button> </div> </form> </div> </div> </main> I am not sure … -
conditional constraints for django model
I have database model like this ActionType = ( (1,"PostBack"), (2,"Uri"), ) class RichMenu(BaseModel): key = m.CharField(max_length=64,unique=True) action_type = m.IntegerField(choices=ActionType,default=1) url = m.CharField(max_length=255,blank=True,null=True) name = m.CharField(max_length=255,blank=True,null=True) Now I would like to make constraint like this, When action_type is 1, url should be null and name should not be null When action_type is 2, name should be null and url should not be null Is it possible to make conditional constraints for this case? -
Nginx can't load static files, did I set wrong path?
I tried setting up nginx with docker on my django project. I checked the volume exists on docker container. And I do have access to my swagger path, but staticfiles does not load. What else can I attempt? Thanks... For example, as settings.py has set the path: # Static files STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") and here is nginx/nginx.conf, may see locaiotn in http: events { worker_connections 1024; } http { upstream django { server web:8000; } server { server_name localhost; access_log off; listen 80; location /static/ { alias /app/staticfiles/; } location / { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } } And finally, docker-compose script: version: '3.8' services: web: build: . command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 --timeout 120 --workers 3 volumes: - .:/app - static_volume:/app/staticfiles ports: - "8000:8000" depends_on: - redis nginx: image: nginx:latest volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro - static_volume:/app/staticfiles ports: - "80:80" depends_on: - web ...... volumes: static_volume: -
Como aplico estilos a un img de un modelo en Django? [closed]
Quiero aplicar estilos en css a los img para que queden centrados y del mismo tamaño pero no se aplica ninguno, intenté de varias formas hasta utilicé chatgpt y aún asi no pude arreglar este problema que tengo. aquí el código class Taza(models.Model): nombre = models.CharField(max_length=20, verbose_name="Nombre") imagen = models.ImageField(upload_to='img/tazas') def __str__(self): return self.nombre def imagen_url(self): return self.imagen.url <div class="container d-flex justify-content-center"> <section class="layout"> {% for ta in taza %} <div><img src="{{ ta.imagen_url }}" alt="{{ ta.nombre }}"></div> {% endfor %} </section> </div> .layout { width: 1366px; height: 768px; display: grid; grid-template-rows: repeat(3, 1fr); grid-template-columns: repeat(3, 1fr); gap: 8px; } div.layout img { max-width: 100%; height: auto; } -
Django queryset remove all duplicates(not just remove one of them)
for example, I have a queryset1 = [objects1, objects2, objects2, objects3] and I know queryset1.distinct() can return [objects1, objects2, object3] but I don't want the objects2 anymore cause there could be some issues so what I want to get is [objects1, object3] -
Django : What is the best way to Generic list (Product) and detail view (Category)
It is better to use class based view or function view? use get_absolute_url or slugify? How to use for and if to display categories in the menu? Some issues are really confusing And it is impossible to understand which way is the best views.py: class ProductView(ListView): template_name = 'main/Html/html_components.html' model = Product class ProductCategoryView(DetailView): model = ProductCategory url: urlpatterns = [ path('', ProductView.as_view(), name='Product'), path('category/', ProductCategoryView.as_view(), name='category-detail'), # path('<int:pk>/', ProductCategoryView.as_view(), name='category-detail'), # path('category/<slug:slug>/', ProductCategoryView.as_view(), name='category-detail'), ] html: html(for loop) {% load static %} <nav class="menu__main"> <ul class="menu"> {% for ProductCategory in ProductCategory %} <li class="single"> <a href="" class="single__link"> <span class="single__text">{{ ProductCategory.title }}</span> </a> </li> <li class="dropdown"> <a href="javascript:void(0);" class="active dropdown__link"> <span class="dropdown__text">Forms</span> <svg class="dropdown__arrow"><use href="#arrow-down"></use></svg> </a> <ul class="dropdown__list"> <li class="dropdown__list__item"> <a href="" class="dropdown__list__link"> <span class="dropdown__list__text">Checkbox</span> </a> </li> <li class="dropdown__list__item"> <a href="" class="dropdown__list__link"> <span class="dropdown__list__text">Radio</span> </a> </li> </ul> </li> {% endfor %} </ul> </nav> models:py class ProductCategory(models.Model): title = models.CharField(max_length=100, null=False, blank=False, unique=True, verbose_name='Title') slug = models.SlugField(max_length=300, blank=True, unique=True, verbose_name='slug') create_date = models.DateTimeField(auto_now_add=True, verbose_name='Create Date') class Meta: verbose_name = 'Category' def __str__(self): return self.title class Product(models.Model): title = models.CharField(max_length=200, null=False, blank=False, unique=True, verbose_name='Title') slug = models.SlugField(max_length=300, allow_unicode=True, null=False, blank=False, unique=True, verbose_name='slug') category = models.ForeignKey('ProductCategory', null=True, blank=True, db_index=True, on_delete=models.CASCADE, verbose_name='Category Parent') class … -
Django Facebook Login Authentication
I had an application that was using Facebook to login and authenticate. However from May onwards something happen and now users when trying to go to the site they are getting this error message. import os from pathlib import Path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 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 = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'paymentlist', 'bootstrap_datepicker_plus', 'bootstrap4', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'django.contrib.sites', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', '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', 'django_user_agents.middleware.UserAgentMiddleware', ] ROOT_URLCONF = 'paymesite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'microsoft_auth.context_processors.microsoft', ], }, }, ] WSGI_APPLICATION = '' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases # # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': str(os.path.join(BASE_DIR, "db.sqlite3")), # } # } DATABASES = { 'default': { 'ENGINE': '', 'NAME': , 'USER': , 'PASSWORD': , 'HOST': , 'PORT': , … -
How to fix "django.core.exceptions.ValidationError: ['Il valore "" ha un formato di data non valido. Deve essere nel formato AAAA-MM-GG.']"
**model.py ** class Customer(models.Model): n_tessera = models.CharField(max_length=200, null=True, default='ABC123') nome = models.CharField(max_length=200, null=False) cognome = models.CharField(max_length=200, null=False) email = models.CharField(max_length=200, null=True) tel = models.CharField(max_length=200, null=True) via = models.CharField(max_length=200, null=True) cap = models.IntegerField(null=True) provincia = models.CharField(max_length=2, null=True) comune = models.CharField(max_length=200, null=True) citta_nascita = models.CharField(max_length=200, null=True) data_nascita = models.DateField(blank=True, null=True) scadenza_certificato_medico = models.DateField(default='', null=False) importo_qa = models.FloatField(null=True, default=0) tipo_qa = models.CharField(choices=[('SR', 'SR'), ('SPC', 'SPC'), ('CF6.0', 'CF6.0'), ('CF6.0 Ridotte', 'CF6.0 Ridotte')], null=False, default='SR', max_length=20) note = models.CharField(max_length=200, null=True, default='--Nessuna nota--') attivo = models.BooleanField(default=True) def __str__(self): return self.nome + " " + self.cognome class Meta: verbose_name = "Cliente" verbose_name_plural = "Clienti" **views.py ** def new_customer(request): if request.method == 'POST': print(request.POST) form = CustomerForm(request.POST) print(form) if form.is_valid(): form.save() return redirect('lista_clienti') # Nome dell'URL della lista dei trainer else: print(form.errors) else: form = CustomerForm() return render(request, 'new_customer.html', {'form': form}) **forms.py ** class CustomerForm(forms.ModelForm): data_nascita = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) class Meta: model = Customer fields = ['nome', 'cognome', 'via', 'cap', 'provincia', 'comune', 'citta_nascita', 'data_nascita', 'attivo', 'tel', 'email', 'note'] testing: from crm_ff.models import Customer new_customer = Customer(nome='Mario', cognome='Rossi', via='Via Roma 1', cap='00100', provincia='RM', comune='Roma', citta_nascita='Roma', data_nascita='1990-01-01', attivo=True, tel='1234567890', email='mario.rossi@example.com', note='Nessuna nota') new_customer.save() Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 364, in runcode coro = func() ^^^^^^ File "", … -
Can anyone help me with this situation [closed]
Reference Image const library = (await(await fetch( ' ./indexData/theLibrary.json')) .json()) const uniquelD = (await(await fetch(• ./indexData/uniqueid .json')).json()) I was trying to load static files like this javascript file using django But can't figure out the source of error here, My editor shows no error and this file ran perfectly fine until i added it to django. Can you please point out what i am missing here -
Can't access media files in nginx
I have a problem that I can't access any of /media files on my development instance of nginx with django. I'm getting 404 every time I do requests to /media my nginx conf file server { listen 80; server_name _; server_tokens off; client_max_body_size 20M; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; } location /api { try_files $uri @proxy_api; } location @proxy_api { proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://backend:8000; } location /media { root /home/user/backend/media/; } } docker-compose version: "3.8" services: # Database service database: container_name: adverity-transformer-challenge-database image: postgres:9.6-alpine environment: POSTGRES_DB: transformer POSTGRES_HOST_AUTH_METHOD: trust ports: - "5433:5432" restart: unless-stopped networks: - djangonetwork # Async tasks broker service redis: container_name: adverity-transformer-challenge-redis image: redis:6 ports: - "6379:6379" restart: unless-stopped # Async tasks worker celery: container_name: adverity-transformer-challenge-celery build: context: ./backend/ dockerfile: Dockerfile.development image: adverity-transformer-challenge-backend environment: BROKER_URL: redis://redis:6379 DATABASE_HOST: database DATABASE_USER: postgres DATABASE_NAME: transformer command: watchmedo auto-restart --pattern '*.py' --signal SIGINT --recursive -- celery -A transformer worker -l debug volumes: - ./backend/:/home/user/backend/:delegated # Main backend application backend: container_name: adverity-transformer-challenge-backend build: context: ./backend/ dockerfile: Dockerfile.development image: adverity-transformer-challenge-backend ports: - "8000:8000" environment: BROKER_URL: redis://redis:6379 DATABASE_HOST: database DATABASE_USER: postgres DATABASE_NAME: transformer volumes: - … -
Django its not printing on HTML
I am trying to understand why Django its not printing on my HTML page, the user db its printing just fine but my ticket db its not being printed, it actually creates the space to allocate the information, as its shown on the image, but it doesn't fill the information on it. views.py #The actual page def dashboard(request): ticket = Userdb.objects.filter(userid = request.user.id) context = {'ticket': ticket} return render(request,'dashboard/home.html', context) #Data in the ticket def ticketr(request): data = {} if request.method == 'POST': if request.POST.get('nomctt') and request.POST.get('tiposerv') and request.POST.get('areaserv') and request.POST.get('tickettext'): table = Userdb() table.nomctt = request.POST.get('nomctt') table.numctt = request.POST.get('numctt') table.tiposerv = request.POST.get('tiposerv') table.areaserv = request.POST.get('areaserv') table.tickettext = request.POST.get('tickettext') table.userid = request.user table.save() data['msg'] = 'Ticket registrado!' data['class'] = 'alert-success' return render(request,'dashboard/home.html', data) else: data['msg'] = 'Preencha todos os campos!' data['class'] = 'alert-danger' return render(request,'dashboard/ticket.html',data) home.html {% block content %} {% if request.user.is_authenticated %} <nav class="navbar"> <div class="navbar__container"> <a href="/" id="navbar__logo"><img src="{% static 'images/logo.png' %}" style="width:180px;height:100px;"></a> <div class="navbar__toggle" id="mobile-menu"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </div> <ul class="navbar__menu"> <ul class="navbar__menu"> <li class="navbar__item"> <a href="/" class="navbar__links"> {{ user.username }} </a> </li> <li class="navbar__btn"> <a href="/loginv" class="button"> Logar </a> </li> </ul> </div> </nav> <a href="/dashboard/ticket/">Abra um Ticket</a> </div> <br> <div class="container bootdey"> … -
Getting invalid name(s) given in select related
I am getting the error invalid field name(s) given in select_related: ‘author_set’. Choices are : first_name, last_name, city, state, country Below are my models: class Author(models.Model): first_name = models.CharField(null=True, blank=True, max_length=50) last_name = models.CharField(null=True, blank=True, max_length=50) city = models.CharField(null=True, blank=True, max_length=50) state = models.CharField(null=True, blank=True, max_length=50) country = models.CharField(null=True, blank=True, max_length=50) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(null=True, blank=True, max_length=50) narration = models.CharField(null=True, blank=True, max_length=200) released = models.DateField() The below command is raising the error authors = Author.objects.select_related(“author_set”) I have tried to use researched and don’t know why -
Change the table name of the Model in django admin
I want to change my django admin table name in django admin panel I want to change the Products name in the top of that table, for example I want to change PRODUCTS and ACCOUNTS names in the picture below: django admin panel side menu In the picture above I have Two model. first is the محصولات and the second one is the نظرات And also my app name is Products which is the shown in the table name. but I want to change this name. and if possible I want to change the other table names which is the "ACCOUNTS". I did change my model verbose_name and verbose_plural_name as you can saw, but I couldn't change the table name. -
Best way to import models from a bunch of different django projects
Basically I have a project that has a bunch of microservices and a number of databases across them. What I want is to create another service that I can run different scripts on that make some changes to the prod db. For example if there was a bug that messed up some records, I'd have to go in to the prod db and fix those records. What would be the best way to import all these models? I want to be able to do something like service_a.db.ModelA service_b.db.ModelB etc Or is there a package I can use to do this already instead of trying to build my own? -
installing a django_url_alias module
I have a requirement of creating a external URI which is different from internal URI. External URI will be configured/created by Website user and Internal URI will be created on the fly by Application itself. Module django_url_alias perfectly fits in my requirement. I have followed the process of installation as mentioned in the Readme file. https://github.com/ddanier/django_url_alias#installation however when i am trying to access the home page, I am getting following error : AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF' after toubleshooting i think it is because i have not followed below step: Replace settings.ROOT_URLCONF with "django_url_alias.urls" Since it is still referring to ROOT_URLCONF instead of django_url_alias.urls. Please help by suggesting how to make above mentioned change. Thanks in advance. made changes to settings.py as below : '# ROOT_URLCONF = 'TestApp.urls'' 'URL_ALIAS_MODULES = URLAliasModule' 'URL_ALIAS_ROOT_URLCONF = 'TestApp.urls'' and following in the template.html file : `{% load url_alias %}` -
Adding tags to identify notes in a django website?
I am currently working on a django project where you can upload course materials, have a personal calendar with notes and a to-do list. I am working on the notes and a personal feature I would like to add is I would either like to be able to attach the notes to a class, or I would like to be able to add identifying tags that would group the notes. Maybe even make it so that when they "enroll" in a paticular class, it automatically creates a folder for that class for them to add notes to. Could anyone shed some light on possible ways I could accomplish this? So far, I only have the ability to create notes, edit and delete them. -
Ordereddict has no attribute caled "..."
I'm trying to upload an object in json format using api_view(), in django-rest-framework. serializers : class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'title', 'description', 'unit_price', 'price_with_tax', 'slug', 'inventory', 'collection'] price_with_tax = serializers.SerializerMethodField(method_name='calculate_tax') def calculate_tax(self, product: Product) : return product.unit_price * Decimal(1.1) views: @api_view(['GET', 'POST']) def product_list(request): if request.method == 'GET': queryset = Product.objects.select_related('collection').all() serializer = ProductSerializer(queryset, many=True, context={'request':request}) return Response(serializer.data) elif request.method == 'POST': serializer = ProductSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.validated_data return Response(serializer.data, status=status.HTTP_201_CREATED) Collection and Products models: class Collection(models.Model): title = models.CharField(max_length=255) featured_product = models.ForeignKey( 'Product', on_delete=models.SET_NULL, null=True, related_name='+', blank=True) def __str__(self) -> str: return self.title class Meta: ordering = ['title'] class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(null=True, blank=True) unit_price = models.DecimalField( max_digits=6, decimal_places=2, validators=[MinValueValidator(1)]) inventory = models.IntegerField(validators=[MinValueValidator(0)]) last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotions = models.ManyToManyField(Promotion, blank=True) this is the object I'm trying to upload and create: { "title": "a", "slug": "a", "unit_price": 1, "collection": 1, "inventory": 1, } I tried to get rid of the calculate_tax part, because the error raised in that part but nothing really crossed my mind besides that -
How should mysql.connector be shared correctly with threads in Django applications?
This concerns a potential solution to my earlier question in which I was getting commands out of sync; you can't run this command now after wrapping mysql cursors in __enter__ and __exit__. I have read elsewhere that Django does not spawn new threads to handle multiple requests, but rather multiple Django processes would normally be spawned in order to achieve parallelism. Despite this advice, I began printing Thread.ident and Thread.native_id and noticed that they were changing. Based on this, I speculatively wrote something like: def db_connect (): t = threading.current_thread() if not hasattr (t, 'db_connection'): print (f"New MyDBConnectionClass for {t.ident}~{t.native_id}") t.db_connection = MyDBConnectionClass () return t.db_connection.get_cursor () # This object has a __exit__ which closes the cursor along with class MyDBConnectionClass (): def __del__(self): t = threading.current_thread() print (f"MyDBConnectionClass deleted for {t.ident}~{t.native_id}") the view handlers' usage of the cursors is unchanged: with db_connect() as db: results = db.all (query, args) So far this seems to have fixed the commands out of sync error (and the exit code 245 crash mentioned in the original question). MyDBConnectionClass.__delete__ is not being called, but various instances are created for a few different ident values. My current hypothesis is that there is some sort of … -
Getting 'invalid ELF header' when running `docker-compose up` Django app?
I have a Django project I am trying to get running in Docker. Apologies in advance- I am very new to Docker and am probably doing something (things?) very wrong. I have the following Dockerfile: FROM python:3.9 ENV PYTHONUNBUFFERED 1 RUN mkdir /my-project WORKDIR /my-project ADD . /my-project/ RUN pip install -r requirements.txt Have the following .dockerignore file: # Git .git .gitignore # Docker Dockerfile .dockerignore # Byte-complied / optimized / DLL files **/__pycache__/ **/*.py[cod] # Django migrations **/migrations/*.py !**/migrations/__init__.py # Swap files **/*.swp # venv files venv/ .env # Sphinx build files docs/_*/ Following docker-compose.yml: version: '3' services: web: build: . command: bash -c "python manage.py runserver 0.0.0.0:8000" container_name: my-project volumes: - .:/my-project ports: - "8000:8000" When I run docker-compose up, it runs until it hits the execution of RUN pip install -r requirements.txt, when I get the following error: error while loading shared libraries: /usr/local/bin/../lib/libpython3.9.so.1.0: invalid ELF header What am I doing wrong? -
How can I tell Django not to load a certain column from the DB
I’m beginning to learn more about improving my app’s performance, and I know while querying I can tell Django to only load the columns I want from the db by using the only method like the code below: books = Books.objects.only("author", "title") What if I want Django to retrieve books but not retrieve the narration column. Please help. Thank you in advance I have tried to include all columns except the narration column and that’s too stressful. I believe there should be a way to exclude only one column. -
correct incorrect serilization in django
After serialization,I tried to call Django-rest api by connecting 3 tables, then I got issue Original exception text was: 'Store' object has no attribute 'Storeimage'., I'm expecting to get api by connecting 3 models. My models class Store(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) address = models.ForeignKey(Address, null=True,on_delete=models.CASCADE) store_name = models.CharField(max_length=255) store_about = models.CharField(max_length=255,null=True) store_location = models.CharField( max_length=255) #store_address = models.TextField() store_phoneno = models.CharField(max_length=12) class Storeimage(models.Model): store = models.ForeignKey(Store, null=True, on_delete=models.SET_NULL) picture = models.ImageField(upload_to='store_image/%Y/%m/',max_length=255,null=True) class Address(models.Model): street = models.TextField() country = models.ForeignKey(Country, default=1,null=True, on_delete=models.CASCADE) state = models.ForeignKey(State, default=1,null=True, on_delete=models.CASCADE) my serilzation class StoreGetSerialiser(serializers.ModelSerializer): #store_product = StoreproductSerializer(many=True) address = AddressSerializer() Storeimage = StoreImage(many=True) owner = UserPublicSerializer(source='user', read_only=True) class Meta: model = Store fields = [ 'pk', 'owner', 'store_name', 'Storeimage', 'store_location', 'address', 'store_phoneno', 'store_website', ] Myexpected output: { "pk": 2, "owner": { "id": 1 }, "store_name": "", "store_location": "", "address": { "id": 14, "street": "1", "country": 1, "state": 1, "city": 1 }, "store_phoneno": "", "store_image": [{"pk":1,"picture":"/location/abcd"},{"pk":2,"picture":"/location/abcd"}] }, -
The post counter not working in my Django project
I am doing a project for my Django course and I hit a wall that I cannot overcome. I tried to find the answer here, but the seems similar to what I already have put in place. So, my project is a forum and posts can be made inside a category. The index page shows the different categories and the amount of posts inside each category. However, no matter how many posts are created the counter does not change. This is the model for the category and for the post class Category(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) content = models.TextField() featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) posts = models.ManyToManyField( 'Post', related_name='categories', blank=True) class Meta: ordering = ['created_on'] def __str__(self): return self.title def number_of_posts(self): return self.posts.count() class Post(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="posts_list") content = models.TextField() featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) likes = models.ManyToManyField(User, related_name='post_likes', blank=True) favourite = models.ManyToManyField( User, related_name='favourite', blank=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name='category') class Meta: ordering = ['created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() def number_of_comments(self): return self.comments.count() this is … -
how to connect Django project to mongoDB?
i have django project where its connected to the default sqlite3 database i want to change the database to the mongoDB but its not working i am using the below packages settings.py: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': '3DHologram', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://testdevleb:JmqUI7qNMB4hvfil@cluster0.dofcak0.mongodb.net/3DHologram?retryWrites=true&w=majority', 'username': 'testdevleb', 'password': 'JdcdUI7kNMB4hvfil', 'authMechanism': 'SCRAM-SHA-1', 'authSource': 'admin', } } } packages: Django==4.1.13 djongo==1.2.3 dnspython==2.4.2 pymongo==3.10.1 pytz==2023.3.post1 once i try the below command python manage.py migrate error: File "F:\private_projects\videoproject\myvenv\Lib\site-packages\django\db\utils.py", line 126, in load_backend raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3'