Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Base template does not render content from {% block content%} on HTML page
I am trying to use a template to be able to reuse a flexbox across multiple pages; rather than reuse the code on each page. However, rather than getting the flexbox I get: If I just render the html as a page to be sure the flexbox works I get the expected output: My html templates are all located in: /Resilience_Radar/Resilience_Radar_App/templates/Resilience_Radar_App/ I setup the layout.html file to include the stylesheet defining the container and added teh templates tags: <!DOCTYPE html> <html lang = "en"> <meta name="viewport" content="width=device-width, initial-scale=1"> <head> <link rel="stylesheet" href="styles.css"> <title>Resilience</title> </head> <body> <h1>Risk Resilience</h1> {% block linesofoperation %} {% endblock %} </body> </html> I the created a file linesofoperation.html that contained the desired code to use in the block: {% extends "layout.html" %} {% block linesofoperation %} <div class="container" style="top: 10%;"> <div class="item_LoO_Name"> <div class="t1">LoO</div> <div class="t2">Implement, maintain and improve a business countinuity management system</div> </div> <div class="space"></div> <div class="item">Context of the Organization</div> <div class="space"></div> <div class="item" style = "background-color:gray">Leadership</div> <div class="space"></div> <div class="item" >Policy</div> <div class="space"></div> <div class="item">Planning</div> <div class="space"></div> <div class="item">Support</div> <div class="space"></div> <div class="item">Operation</div> <div class="space"></div> <div class="item">Management Review</div> <div class="space"></div> <div class="item">Improvement</div> <div class="space"></div> <div class="triangle-right"></div> <div class="spaceblank"></div> <div class="item_LoO_Name" style="background-color: white; color: … -
How to use django/jinja tags to extend an html with a javascript snippet from another .js file
I am developing a django app. There is a file templates/index.html file having some javascript snippets at its footer, such as ... </body> </html> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <!-- load jquery. I put this after leaflet --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- import a library leaflet.browser.print from local folder lib placed in the staticfiles folder --> <script src="{% static './lib/leaflet.browser.print.min.js' %}"></script> There is also a file templates/publish_layers_in_html_page.html which contains a javascript snippet using jinja tags, the content is the following <script> var overlayMaps = {}; // Shapefile wms {% for s in shp %} var {{ s.name }} = L.tileLayer.wms('http://localhost:8080/geoserver/wms', { layers: '{{s.name}}', transparent: true, format: 'image/png', }) overlayMaps['{{ s.name }}'] = {{ s.name }} {% endfor %} L.control.layers(baseMaps, overlayMaps, {collapsed: false, position: 'topleft'}).addTo(map) </script> Is it possible to use django tag {% extends %} to insert this javascript snippet into the index.html file? I have tryed to change the two files as follows, but with no success. index.html ... </body> </html> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <!-- load jquery. I put this after leaflet --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- import a library leaflet.browser.print from local folder lib placed in the staticfiles folder --> <script src="{% static './lib/leaflet.browser.print.min.js' %}"></script> {% block scripts %}{% endblock %} publish_layers_in_html_page.html {% extends … -
Jdango arm join the same table twice using alias
We are using jango models. I'd need to add one more condition to join the same table twice with different conditions. Sample query: select shop_id from shop_to_warehouse_mapping inner join warehouse w1 on w1.id = shop.warehouse_id inner join warehouse w2 on w2.id = shop.warehouse_id where w1.type='daily_life' and w2.type='produce' We have shop to warehouse mappings, that's many to many. I'd like to get the shop ids that are working with both warehouse 1 and 2. In the Django models, we have the foreign key of warehouse on the shop to warehouse mapping model. How can I use filter method to represent this? If I could using alias somehow in the filter, that'd be great. Any help's appreciated! (I'd love to write the query directly, but this query's complex having many other conditions already). thanks! -
Elegant way to add a link next to the APP name in Django Admin
See photo below, I want to add a link next to "APP1", I had searched google and seems only one way to do it by overriding the admin template app_list.html then see if app name is "APP1" then add the link. <caption> <a href="{{ app.app_url }}" class="section" title="{% blocktranslate with name=app.name %}Models in the {{ name }} application{% endblocktranslate %}">{{ app.name }}</a> </caption> I've tried the verbose_name approach but it didn't want render properly even with mark_safe(), let alone what else this verbose_name will be used and cause more issues, so I am opting out this approach. verbose_name = mark_safe('APP1 <a href="/somehwere">link</a>') So apart from overriding the template, is there anything else I can do? -
Cron is not inheriting environment variables in Docker container
I am trying to run cron inside a Docker container to periodically update my database, perform backups, etc. Here is my cron job configuration: */1 * * * * (. /app/.env.development; echo $DJANGO_COLOR) >> /var/log/cron.log 2>&1 */1 * * * * (. /app/.env.development; /usr/local/bin/python3 /app/src/manage.py command) >> /var/log/cron.log 2>&1 */1 * * * * (export $(cat /app/.env.development | grep -v "^#" | xargs); /usr/local/bin/python3 /app/src/manage.py command) >> /var/log/cron.log 2>&1 The problem: The cron job does not inherit the environment variables from my Docker container. I tried loading the environment variables with . /app/.env.development, which works for the first line, but for some reason, the Django server runs without the environment variables in the second and third lines. The cronjob Dockerfile: FROM app as cron RUN apt-get update && apt-get -y install cron # Copy hello-cron file to the cron.d directory COPY cron/app-cron /etc/cron.d/app-cron # Give execution rights on the cron job RUN chmod 0644 /etc/cron.d/app-cron # Apply cron job RUN crontab /etc/cron.d/app-cron # Create the log file to be able to run tail RUN touch /var/log/cron.log Entrypoint: /bin/bash -c "cron && tail -f /var/log/cron.log" Can you please explain why this is happening? How can I ensure that the cron job … -
CSS not working after applying collectstatic in Django
I just deployed my django project on nginx server. I have connected with domain and everything, site is live. However, the issue occured when I used python3 manage.py collectstatic. Everything still works, but css is not loaded and site is not looking how it supposed to be. Here is some code and options that I tried. parts from settings.py BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['my-wow-site.com', 'www.my-wow-site.com', 'xx.xx.xxx.xx'] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] urls.py urlpatterns = i18n_patterns( path(_('admin/'), admin.site.urls), path('rosetta/', include('rosetta.urls')), path('', include('main_app.urls', namespace='main_app')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), path('ckeditor/', include('ckeditor_uploader.urls')), ) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) I have everything uploaded/deployed in root folder... and I have set up this by using command sudo nano /etc/nginx/sites-available/default content is... server { listen 80; server_name my-wow-site.com www.my-wow-site.com; return 301 https://$host$request_uri; root /root/wow_site/ location /static/ { alias /root/wow_site/staticfiles/; } location /media/ { alias /root/wow_site/media/; } } server { listen 443 ssl; server_name my-wow-site.com www.my-wow-site.com; ssl_certificate /etc/nginx/ssl/nginx.crt; ssl_certificate_key /etc/nginx/ssl/nginx.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { proxy_pass http://localhost:8000; # Adjust as necessary for your application 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; } } Usually sources … -
Django wizard form and htmx partials
I am building a django wizard form with multiple form, however in one of the forms i have a field of small list of sectors, and when the user select a sector i trigger a function that fetches the sub-sectors of that particular sector. the problem is when i tested the form in a separated html template it works fine, but when i use it in my wizard form it does not update the ui even though in the console i can see that the request was successful. #urls.py from django.urls import path # type: ignore from django.utils.translation import gettext_lazy as _ # type: ignore from core import views app_name = 'core' urlpatterns = [ path('', views.OnboardingSessionWizardView.as_view(views.FORMS), name='start'), path('sub-sectors/', views.get_subsectors, name='get-sub-sectors'), path('get-started/', views.OnboardingSessionWizardView.as_view(views.FORMS), name='get-started'), ] here is my view.py: from core.forms import * from formtools.wizard.views import SessionWizardView # type: ignore from django.http import HttpResponse, JsonResponse, HttpRequest # type: ignore from django.utils.translation import gettext_lazy as _ # type: ignore from django.shortcuts import render,get_object_or_404 # type: ignore from django.core.serializers import serialize # type: ignore from core.models import * from core.forms import * # Create your views here. FORMS = [("contact", EntryInformationForm), ("information", PersonalInformationForm), ("business", BusinessActivityForm), ("address", BusinessAddressForm), ] TEMPLATES = { "contact": … -
How to implement follow/unfollow functionality without reloading the page in Django
I am building a web application using Django where users can follow or unfollow items (e.g., photos) from a list. Currently, I have implemented the follow/unfollow functionality, but it reloads the page every time the user clicks on follow or unfollow. I want to achieve this without reloading the page, so the user stays on the same page and the state changes (follow/unfollow) are reflected immediately. models.py class UserProfile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) follows = models.ManyToManyField(Photo, related_name='followers') def __str__(self): return self.user.username views.py from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from .models import Photo, Episode, UserProfile def viewPhoto(request, pk): photo = get_object_or_404(Photo, id=pk) episodes = Episode.objects.filter(photo=photo) if request.user.is_authenticated: user_profile, created = UserProfile.objects.get_or_create(user=request.user) is_following = photo in user_profile.follows.all() else: is_following = False context = { 'photo': photo, 'episodes': episodes, 'is_following': is_following, } return render(request, 'photos/photo.html', context) @login_required def follow(request, pk): photo = get_object_or_404(Photo, id=pk) user_profile, created = UserProfile.objects.get_or_create(user=request.user) user_profile.follows.add(photo) return redirect('photo', pk=pk) @login_required def unfollow(request, pk): photo = get_object_or_404(Photo, id=pk) user_profile, created = UserProfile.objects.get_or_create(user=request.user) user_profile.follows.remove(photo) return redirect('photo', pk=pk) html {% if is_following %} <div class="btn follow"> <a href="{% url 'unfollowPhoto' photo.id %}">Unfollow</a> </div> {% else %} <div class="btn follow"> <a href="{% url 'followPhoto' photo.id %}">Follow</a> </div> {% endif %} … -
Django RF deserialization
In django rest framework when we call post request in which we send json data to be saved in database.so how django RF handle this request and how will it receive json data how will it convert into python native and then complex data type? What's the role of Bytes io function in this? I just can't understand process. -
In Django with DjangoCMS how do I reverse an URL when using the sites framework (the URL is on a different site)?
I have a Django install with DjangoCMS and ~20 sites (with Djangos sites framework). I would like to create a link from one site (https://a.example.com/) to another site (https://b.example.com/). For example I have an CMSApp called persons and a single URL for example https://a.example.com/en/person/aaa/ and https://b.example.com/de/team/aaa/. If I try to reverse it like this on a.example.com: reverse("persons:canonic-person", kwargs={"person_slug": self.slug}) I get: /en/person/aaa/ But I want to be able to switch to b.example.com and get /de/team/aaa/ or even better: https://b.example.com/de/team/aaa/. How do I achieve that? -
How to resolve that after searching request a property name has changed to a property id?
I am using a React Native Expo web app for the frontend and Django for the backend. I have a search function that works fine. But the problem I am facing is that after a search term the property name of a specific animal has changed to a property id (number). What I mean with this is that in the accordion the category name is shown. But after the search the category id is displayed. In the frontend I have an accordion with some properties. The property for category looks: export const AccordionItemsProvider = ({ children }) => { const [categoryExpanded, setCategory] = useState(false); const accordionItems = (item) => { return ( <> <List.Accordion title="Familie" expanded={categoryExpanded} onPress={() => setCategory(!categoryExpanded)}> <Text>{item.category}</Text> </List.Accordion> </> ); }; return ( <AccordionItemsContext.Provider value={{ accordionItems, }}> {children} </AccordionItemsContext.Provider> ); }; So the name of category will be displayed. But after the search the id of category will be displayd. And not the name. The search context of animal looks: /* eslint-disable prettier/prettier */ import React, { createContext, useEffect, useState } from "react"; import { fetchAnimalData } from "./animal/animal.service"; import useDebounce from "../hooks/use-debounce"; export const SearchAnimalContext = createContext(); export const SearchAnimalContextProvider = ({ children }) => { … -
Error processing file n.mp4: int() argument must be a string, a bytes-like object or a real number, not 'list'
i am trying to convert and compress the given videos to the given video format but getting the following error: Error processing file n.mp4: int() argument must be a string, a bytes-like object or a real number, not 'list'. i don't know why the function convert_video_to_video is taking compression_percentage as a list. following is my django view: import os import io import zipfile import re import logging import subprocess from concurrent.futures import ThreadPoolExecutor from django.conf import settings from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from moviepy.editor import VideoFileClip import boto3 from moviepy.video.fx import all as vfx from asgiref.sync import async_to_sync from channels.layers import get_channel_layer logger = logging.getLogger(__name__) class CompressVideoView(APIView): def post(self, request, *args, **kwargs): logger.debug("Received video conversion request") files = request.FILES.getlist('files') s3 = boto3.client('s3') bucket_name = settings.AWS_STORAGE_BUCKET_NAME folder = 'videos/' video_formats = request.data.getlist('formats') screen_size = request.data.getlist('screen_size', 'no-change') frame_rate = request.data.getlist('frame_rate', 'no-change') rotate = request.data.getlist('rotate', 'no-change') flip = request.data.getlist('flip', 'no-change') subtitle = request.data.getlist('subtitle') copy_subtitles = request.data.getlist('copy_subtitles') remove_subtitles = request.data.getlist('remove_subtitles') volume = request.data.getlist('volume') fade_in = request.data.getlist('fade_in') fade_out = request.data.getlist('fade_out') remove_audio = request.data.getlist('remove_audio') trim_start_h = request.data.getlist('trim_start_h', 0) trim_start_m = request.data.getlist('trim_start_m', 0) trim_start_s = request.data.getlist('trim_start_s', 0) trim_end_h = request.data.getlist('trim_end_h', 0) trim_end_m = request.data.getlist('trim_end_m', 0) trim_end_s = request.data.getlist('trim_end_s', 0) # … -
Request.session in django doesnt pass through ajax unless i refresh the page
Request.session in django doesnt pass through ajax unless i refresh the page request.session remains the old one unless i hit refresh to the page any help would appreciated ` $(document).ready(function () { $("#specialty_form").on('change', function (event) { event.preventDefault(); function getCSRFToken() { return $('meta[name="csrf-token"]').attr('content'); } $.ajaxSetup({ headers: { 'X-CSRFToken': getCSRFToken() } }); $.ajax({ type: 'POST', url: '/specialty', data: { specialty: $("#specialty").val(), csrfmiddlewaretoke: $('input[name="csrfmiddlewaretoken"]').val(), }, }) }) });` -
Django and SQL Server GIS error create point
i'm using django and sql server database when i try to create point to my model it keep giving me this error ProgrammingError at /api/common/v1/location/ ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]No column name was specified for column 1 of 'subquery'. (8155) (SQLExecDirectW)") this is my model class Location(TimeStampedWithNamesModel): """this class for general Location model.""" district = models.ForeignKey( District, on_delete=models.CASCADE, related_name="district_locations", null=True, blank=True, ) city_id = models.IntegerField(null=True, blank=True) region_id = models.IntegerField(null=True, blank=True) country_id = models.IntegerField(null=True, blank=True) polygon = models.PolygonField(null=True, blank=True) point = models.PointField(null=True, blank=True) area = models.FloatField(null=True, blank=True) is_polygon = models.BooleanField(default=False) diameter = models.FloatField(null=True, blank=True) class Meta: """this Meta class for the location model.""" ordering = ("-created_at",) unique_together = UNIQUE_TOGETHER_NAME_WITH_COMPANY verbose_name = _("Location") verbose_name_plural = _("Location") and for my setting DATABASES = { "default": { "ENGINE": config( "SQL_ENGINE", default="mssql" ), "NAME": config( "SQL_DATABASE", default="xxx" ), "USER": config("SQL_USER", default="admin"), "PASSWORD": config("SQL_PASSWORD", default="xxxx"), "HOST": config("SQL_HOST", default="xxxxx"), "PORT": config("SQL_PORT", default="1433"), "ATOMIC_REQUESTS": True, "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", } }, } note that another models are work fine I can create and list and update them -
i have made an otp_code function in django and i don't know how to debug it;it shows this error (('QuerySet' object has no attribute 'created_at')) [duplicate]
when i enter the otp_code that comes from the create_otp_code definition it must show me a success message but it returns the below error i have highlighted the line of error on views.py you can find the django codes of the app here in below view.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from account.forms import CustomUserCreationForm, SignInForm import random from django.utils import timezone from datetime import timedelta from django.contrib import messages from .models import * # Create your views here. def signup(request): global form if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('success_massage') else: form = CustomUserCreationForm() return render(request, 'account/signup.html', {'form': form}) def signin(request): if request.method == 'POST': getting_in = SignInForm(request.POST) if getting_in.is_valid(): cd = getting_in.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is not None: login(request, user) return redirect('success_massage') else: getting_in = SignInForm() return render(request, 'account/signin.html', {'form': getting_in}) @login_required def change_password(request): if request.method == 'POST': user = request.user password = request.POST.get('password') confirm_password = request.POST.get('confirm_password') if password == confirm_password: user.set_password(password) user.save() return redirect('success_massage') return render(request, 'change_password.html', {'form': change_password}) @login_required def create_otp_code(request): if request.method == 'POST': code = random.randint(1000, 9999) OtpCode.objects.create(user=request.user, code=code) return redirect('enter_otp_code') return render(request, 'account/create_otp_code.html') … -
Why only one database for django apps in the tutorial?
I'm in need for another application in my django website but fail to understand how to extend my knowledge from the tutorial. Following the tutorial, my project structure looks like this: - mydjango/ - db.sqlite - firstapp/ - mysite/ The tutorial states … An app can be in multiple projects. … My understanding of that quote and django, is, that concerns are separated. However the database handling in the tutorial contradicts that concept. How can an app be in another project? The project's database sits not even in the parent project's directory. Everything is just mixed up in one database. Why does each app not have it's own database? -
django cannot access from same LAN after runserver ip:port
Please help for my problem I'm new in django programming, my rpoblem is when I use localhost can direct to dashboard but when I use Local IP got error message and still in login menu,bellow is error message from console: The Cross-Origin-Opener-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can also use the 'localhost' Refused to execute script from 'http://192.168.0.81:8000/static/vendor/libs/%40form-validation/umd/plugin-bootstrap5/index.min.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. for setting.py ALLOWED_HOSTS = ['192.168.0.81', 'localhost', '127.0.0.1'] SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' -
Most efficient way to store dynamic properties in Django
Let's imagine we have a base like this: class MyModel(models.Model): name = models.CharField(max_lenght=25) # ... some other fields dynamic_properties = models.ManyToManyField("Dynamic") class Dynamic(models.Model): key = models.CharField(max_lenght=25) value = models.CharField(max_lenght=25) MyModel would be the base of all my entries containing its base static data, but when ever I need to add a dynamic property I add it to the dynamic_properties field. While this does make sense on the paper it's kinda inneficient from what's I've been testing so far, let's say each MyModel entries have an average of 4 dynamic properties if I want to iterate over 2k MyModel objects and return all their dynamic properties it is quite slow. I tried to use prefetch_related as the docs suggest but it didn't seem to have a real impact (but that's maybe me misunderstanding how it's used). For the reference I tried it like that: {model.name: model.some_value for model in MyModel.objects.all()} # Is very slow {model.name: model.some_value for model in MyModel.objects.prefetch_related("dynamic_properties")} # Is also very slow Is there a more efficient way to have dynamic properties or is my understanding of prefetch_related wrong and this is the good way ? -
How do calls of models.Manager and custom managers work?
I extended the models.Manager class and created a custom manager. class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset()\ .filter(status=Post.Status.PUBLISHED) It's more than understandable, BUT how do calls of managers work? objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. I don't address get_queryset method, I just call constructors. Then how does it work? -
django.core.exceptions.ImproperlyConfigured: Requested settings | os.environ.setdefault('DJANGO_SETTING_MODULE', 'online_shop.settings') not working
I've been trying to use celery and celery beat with my django project, but I always get the same error: django.core.exceptions.ImproperlyConfigured: Requested settings, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. and here is my celery configuration: from celery import Celery from datetime import timedelta import os from django.conf import settings os.environ.setdefault('DJANGO_SETTING_MODULE', 'online_shop.settings') celery_app = Celery('online_shop') celery_app.config_from_object('django.conf:settings', namespace='CELERY') celery_app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) celery_app.conf.broker_url = 'amqp://guest:guest@localhost' celery_app.conf.result_backend = 'rpc' celery_app.conf.task_serializer = 'json' celery_app.conf.result_serializer = 'pickle' celery_app.conf.accept_content = ['json', 'pickle'] celery_app.conf.result_expires = timedelta(days=1) celery_app.conf.task_always_eager = False celery_app.conf.worker_prefetch_multiplier = 2 but every time I try to run celery like this: celery -A online_shop worker -l info I get that error... I tried this line: export export DJANGO_SETTINGS_MODULE=online_shop.settings but this won't work when daemonizing the process!!! I tried writing it to the .bashrc: the same error. I tried writing it to the activate file in virtual environment, It didn't work either! I also tried to export the variable before running celery in supervisor conf: [program:exporting_to_os] user=ali command=export DJANGO_SETTING_MODULE=online_shop.settings autostart=true autorestart=true stderr_logfile=/var/log/online_shop/exporting.err.log stdout_logfile=/var/log/online_shop/exporting.out.log [program:online_shop_celery] user=ali directory=/home/.../OnlineShop/online_shop/ command=/home/.../OnlineShop/env/bin/celery -A online_shop worker -l info numprocs=1 autostart=true autorestart=true stdout_logfile=/var/log/online_shop/celery.log stderr_logfile=/var/log/online_shop/celery.err.log and still the same error... Please guide me on … -
ModuleNotFoundError: No module named 'captchamptt'
I'm try to install django-machina I read documents and when i run python manage.py migrate i get error for module captchamptt In dependencies there is a library named : 'django-mptt' but i cant find 'captchamptt' library to install Traceback : Traceback (most recent call last): File "C:\Users\Administrator\Desktop\RBtest\RondBazar\manage.py", line 24, in <module> main() File "C:\Users\Administrator\Desktop\RBtest\RondBazar\manage.py", line 20, in main execute_from_command_line(sys.argv) File "C:\Users\Administrator\Desktop\RBtest\projenv\lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\Administrator\Desktop\RBtest\projenv\lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\Administrator\Desktop\RBtest\projenv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Administrator\Desktop\RBtest\projenv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Administrator\Desktop\RBtest\projenv\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Program Files\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'captchamptt' different python versions different virtualenvs different pip version -
"Django: OperationalError - Could not translate host name 'postgres.railway.internal' to address"
I'm encountering an issue while trying to connect my Django application to a PostgreSQL database hosted on Railway. The error I'm getting is: "Django: OperationalError - Could not translate host name 'postgres.railway.internal' to address"` I've double-checked that the hostname and database credentials are correct. What could be causing this hostname resolution issue, and how can I resolve it? Any help would be greatly appreciated! Here is my settings.py configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'railway', 'USER': 'postgres', 'PASSWORD': os.environ.get('DB_PASSWORD_YO'), 'HOST': 'postgres.railway.internal', 'PORT': '5432', } } -
Django- how to convert <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> to an image?
I have a form that uploads an image to my view; the uploaded image type is: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> I want to process the image though; thus I need it in PIL or CV2 format. How can I do that ? -
Error 500 during login and register in django application hosted on heroku servers, while locally everithing work good
When I try to login or register in my django app on heroku server I have an a error 500. However, when I register or login locally I don't have any issues. Here the logs: 2024-08-02T22:17:13.267743+00:00 heroku\[web.1\]: State changed from starting to up 2024-08-03T22:34:20.389130+00:00 heroku\[router\]: at=info method=GET path="/" host=fierce-brook-34882-87d6631e0056.herokuapp.com request_id=34b832f3-b190-4bc2-88ac-576c6dd59905 fwd="80.107.58.61" dyno=web.1 connect=0ms service=137ms status=200 bytes=2493 protocol=https 2024-08-03T22:34:20.389210+00:00 app\[web.1\]: 10.1.62.231 - - \[03/Aug/2024:22:34:20 +0000\] "GET / HTTP/1.1" 200 2197 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0" 2024-08-03T22:34:20.729350+00:00 app\[web.1\]: 10.1.62.231 - - \[03/Aug/2024:22:34:20 +0000\] "GET /favicon.ico HTTP/1.1" 404 1862 "https://fierce-brook-34882-87d6631e0056.herokuapp.com/" "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0" 2024-08-03T22:34:20.729672+00:00 heroku\[router\]: at=info method=GET path="/favicon.ico" host=fierce-brook-34882-87d6631e0056.herokuapp.com request_id=ba080178-f0ef-4d0c-8745-0556273710f1 fwd="80.107.58.61" dyno=web.1 connect=0ms service=28ms status=404 bytes=2165 protocol=https 2024-08-03T22:34:26.884713+00:00 app\[web.1\]: 10.1.94.152 - - \[03/Aug/2024:22:34:26 +0000\] "GET /users/login/ HTTP/1.1" 200 2715 "https://fierce-brook-34882-87d6631e0056.herokuapp.com/" "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0" I also try heroku run python manage.py migrate -
Django drf Serialize group by model field
Django drf Serialize group by model field I have drf endpoint i get this result, but i want to group this result by model field product_type, how i can implement this? i tryed like in this answer DRF: Serializer Group By Model Field but it didn't help me [ { "id": 1, "name": "Danwich ham and cheese", "product_type": "Snacks", "img_url": "https://media.dodostatic.net/image/r:292x292/11EE796FF0059B799A17F57A9E64C725.avif", "grams": 210, "description": "Crispy ciabatta and the familiar combination of ham, chicken, mozzarella with fresh tomatoes, ranch sauce and garlic", "extra_info": "", "price": "3.28", "extra_ingredients": [] }, { "id": 2, "name": "Danwich Chorizo BBQ", "product_type": "Snacks", "img_url": "https://media.dodostatic.net/image/r:292x292/11EE796FF041FE1F94C903576DCFD01E.avif", "grams": 210, "description": "Rich taste of spicy chorizo sausages and spicy pepperoni with burger and barbecue sauces, fresh tomatoes, pickled cucumbers, mozzarella and onions in a golden ciabatta", "extra_info": "", "price": "3.28", "extra_ingredients": [] }, { "id": 3, "name": "Chocolate milkshake", "product_type": "Cocktails", "img_url": "https://media.dodostatic.net/image/r:292x292/11EE796FA24D1E919FA050D8BA21F8E9.avif", "grams": null, "description": "Charming chocolate delicacy. Try a milkshake with cocoa and ice cream", "extra_info": "0.3 L", "price": "2.71", "extra_ingredients": [] }, { "id": 4, "name": "Strawberry milkshake", "product_type": "Cocktails", "img_url": "https://media.dodostatic.net/image/r:292x292/11EE796FB231A5BF82B0A99A1B12339C.avif", "grams": null, "description": "No matter what time of year it is, this cocktail with strawberry concentrate will take you back to summer in one …