Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overload of parentheses operator - passing an argument to predicate functions [duplicate]
This example of operator() overload is clear and straightforward: struct add_x { add_x(int val) : x(val) {} // Constructor int operator()(int y) const { return x + y; } private: int x; }; add_x add42(42); int i = add42(8); assert(i == 50); add_x add42(42) defines a functor with 42 set as private member, next int i = add42(8) calls this functor with 8 as argument. Next operator() adds 42 and 8 and returns 50. Just great. However, how on earth does this example work: std::vector<int> v(10, 2); // some code here struct DivisibleBy { const int d; DivisibleBy(int n) : d(n) {} bool operator()(int n) const { return n % d == 0; } }; if (std::any_of(v.cbegin(), v.cend(), DivisibleBy(7))) std::cout << "At least one number is divisible by 7\n"; DivisibleBy(7) creates an instance of DivisibleBy with 7 set as struct member. How does any_of() realize that it has to pass vector values to DivisibleBy used here as a predicate function? This definitely works: if (std::any_of(v.cbegin(), v.cend(), [](int i) { DivisibleBy db7 = DivisibleBy(7); return db7(i);} )) std::cout << "At least one number is divisible by 7\n"; I define an inline predicate function with explicit int i argument which receives values … -
Error : C1083 Cannot Open Compiler generated file : Permission denied ( VC++2015 )
I am upgrading My VC++ MFC project from 2006 to 2015 , Now I am getting a error This error said cannot open compiler generate file ; Permission denied. I am checking the project properties allow full control , and also allow read write data. but its also not working . Please Help me (: Trying clean and build project not working Give full path in configuration Properties not working . Allow full control to project file not working . -
How to allow characters other than letters, numbers, underscores or hyphens in a Django SlugField
Wikipedia slugs sometimes contain characters other than letters, numbers, underscores or hyphens such as apostrophes or commas. For example Martha's_Vineyard In my Django app I am storing Wikipedia slugs in my model which have been pre-populated from a Wikipedia extract. I use the Wikipedia slug to generate slugs for my Django app's own webpages. I'd therefore like to use SlugField as the field type and have a model field definition of:- slug = models.SlugField(default=None,null=True,blank=True,max_length=255,unique=True) However as you would expect from the Django documentation this throws an error of 'Enter a valid “slug” consisting of letters, numbers, underscores or hyphens.' when there is an apostrophe or comma in the Wikipedia slug. Adding allow_unicode=True did not seem to solve the issue:- slug = models.SlugField(default=None,null=True,blank=True,max_length=255,unique=True,allow_unicode=True,) ChatGPT suggested a custom slug validator as follows but the same error occurred and ChatGPT concluded 'It appears that Django's SlugField is stricter in its validation than I initially thought, and it may not accept commas (,) even with a custom validator':- custom_slug_validator = RegexValidator( regex=r'^[a-zA-Z0-9'_-]+$', message="Enter a valid slug consisting of letters, numbers, commas, underscores, or hyphens.", code='invalid_slug' ) class Route(models.Model): slug = models.SlugField( default=None, allow_unicode=True, null=True, max_length=255, validators=[custom_slug_validator], # Apply the custom slug validator help_text="Enter the … -
Why is docker compose failing with " ERROR [internal] load metadata for docker.io/library/python:3.11.6-alpine3.18 "?
I'm new to docker, trying to build a website by following a online course but i was struck with this error in the beginning itself FROM python:3.9-alpine3.13 LABEL maintainer="rohitgajula" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./app /app WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ /py/bin/pip install -r /tmp/requirements.txt && \ rm -rf /tmp && \ adduser \ --disabled-password \ --no-create-home \ django-user ENV PATH="/py/bin:$PATH" USER django-user Error is [+] Building 1.3s (4/4) FINISHED docker:desktop-linux => [internal] load .dockerignore 0.0s => => transferring context: 191B 0.0s => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 492B 0.0s => ERROR [internal] load metadata for docker.io/library/python:3.9-alpine3.13 1.3s => [auth] library/python:pull token for registry-1.docker.io 0.0s ------ > [internal] load metadata for docker.io/library/python:3.9-alpine3.13: ------ Dockerfile:1 -------------------- 1 | >>> FROM python:3.9-alpine3.13 2 | LABEL maintainer="rohitgajula" I couldn't find solution anywhere. -
IMAGE API DjangoREST
I need guidance on how to write an API in DjangoREST that downloads an image of any size from the user and returns a link to a given image with defined sizes for the user account type (basic, premium, etc.). I have nothing to show because I have already given up many times I tried a few methods from YT and forums.. -
Telling a queryset what is its result so that it does not have to query the database
(Disclaimer: I'm not sure if this is just a stupid question) On my flow, I already have the object I need from the database but I need it in the form of a Queryset to be used later (on annotations and also to use the same code that is used for multiple elements). At the moment I'm just building the query again: queryset = MyModel.objects.filter(id=object.id) But I was trying to know if it would be possible to "hint" the queryset to tell which is the result of it. Something like: queryset.result = object Probably the flow should be revisited and I should not be doing this at all, but before doing any refactoring, I would like to know if something like this is possible. Thank you! -
Using Django forms.ModelMultipleChoiceField and forms.CheckBoxMultipleSelect only returning 1 value (checkbox)
I have a ModelForm: class Form(forms.ModelForm): class Meta: model = ParkingSpace fields="__all__" exclude = [] features = forms.ModelMultipleChoiceField(queryset=Features.objects.all(),widget=forms.CheckboxSelectMultiple) The field features is a m2m relationship in the models. As 1 parking space can have many features and a feature can be related to many parkingspaces. I have used ModelMultipleChoiceField as advised but when I submit this form, only 1 checkbox that I tick (the last one I check) is sent in the post data. This means that when I save the features in the back-end only 1 feature is saved to the database How can I get a list of the checked checkboxes returned in the post data? -
How to make minify compress static file on django website
I have make new website on django link is here https://civiqochemicals.com/ When i m test website on google PageSpeed Insights it show me slow website and error on css js and images file. How to fix ... -
DJANGO: path searched will not match URL patterns
I am new to Django following a tutorial, but cannot get past this error message from Django. I am typing in the file path exactly, but it will not work. enter image description here Here is the website URLs .py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path("hello/", include('testApp.urls')), ] Here is the app's urls .py: from django.urls import path from . import views urlpatterns = [ path('hello/', views.say_hello) ] Here is the app's view.py from django.shortcuts import render from django.http import HttpResponse def say_hello(request): return HttpResponse("Bernz/Shell Boat Parts") --Thank you. I've tried http://127.0.0.1:8000/hello and http://127.0.0.1:8000/testAPP/hello and both have given me the same message that they do not match. Please help: -
Django let a view be seen once a time
I'm new at Django and I would like to make a view available just once per time (I think they're called sessions) Basically, if someone request a page, the page can be access only if nobody is on that page at the same time. If someone is seeing the page and a new request of the same page come in, it should be declined From what I've understood, sessions should help to do it but, I need for both authenticated user and not authenticated ones. Is there a way to do that? I'm seeing solution that limits one session per logged in user, but I need one session per page views -
Working on a django project, webpage loads fine but datas are not fetching from PostgreSQL database
I'm working on a django project. I'm using PostgreSQL database and when I load my webpage, it loads up find but it won't load up the datas from the database. Here are settings.py, models.py, views.py and the html file here. I've spent half of my day trying to fix this. I've no idea what went wrong. Plz help. settings.py (PostgreSQL database) DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "app_name", 'USER' : 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT':'5432', } } models.py class Service(models.Model): index = models.IntegerField(null=True, blank=True) heading = models.CharField(max_length=30) description = models.CharField(max_length=150) icon = models.ImageField(upload_to="services_icons/") def __str__(self): return self.heading views.py def services_view(request): services = Service.objects.all().order_by("index"), return render(request, "service.html", {services : services}) service.html <div class="row"> {% for item in services %} <div class="col-md-4 mb-5"> <div class="d-flex"> <i class="fa fa-3x text-primary mr-4"><img src="{{item.icon.url}}"></i> <div class="d-flex flex-column"> <h4 class="font-weight-bold mb-3">{{item.heading}}</h4> <p>{{item.description}}</p> <a class="font-weight-semi-bold" href="">Read More <i class="fa fa-angle-double-right"></i></a> </div> </div> </div> {% endfor %} </div> I have tried manually deleting the database from the PostgreSQL using pgAdmin4 and re-migrating again. I have also tried flushing the database. python manage.py flush -
Django how to make dinamycally OR queries with ORM
Here is my SQL Query all_or_conditions = [] if request.GET.get('filter_phone'): all_or_conditions.append("phone='"+request.GET.get('filter_phone')+"'") if request.GET.get('filter_email'): all_or_conditions.append("email='"+request.GET.get('filter_email')+"'") if request.GET.get('filter_whatsapp'): all_or_conditions.append("whatsapp='"+request.GET.get('filter_whatsapp')+"'") sql_query = "SELECT * FROM app_table WHERE " + " OR ".join(all_or_conditions) So if only one email is set sql-query will be like SELECT * FROM app_table WHERE email='user@email.com' if email and whatspp SELECT * FROM app_table WHERE email='user@email.com' OR whatsapp='15557776655' So the question is, is it possible to make such query with Django ORM not by performing RAW queries -
Django query spanning multiple relationships with indirection
My question is about querying objects spanning across multiple relationships, with a twist. I don't know how to translate what seems like a simple SQL query into its equivalent in Django. Here's a cut down version of my models (I removed the noise) : class Project(models.Model): title = models.CharField() assigned_users = models.ManyToManyField(User, through="ProjectAssignment") class CostProfile(models.Model): title = models.CharField() default_daily_rate = models.DecimalField() class CostRate(models.Model): project = models.ForeignKey(Project) profile = models.ForeignKey(CostProfile) daily_rate = models.DecimalField() class ProjectAssignment(models.Model): project = models.ForeignKey(Project) user = models.ForeignKey(User) cost_profile = models.ForeignKey(CostProfile) Users can be assigned to multiple Projects, with a given CostProfile as extra field of the many-to-many relationship. A Project also has multiple CostRates, that can override the default daily rate on a ProjectAssignment's CostProfile. I want to list all ProjectAssignments, with the referenced user, the cost profile, its default daily rate and finally the related cost rate if there is one for this project and cost profile. The difficulty is on the last bit : matching the related CostRate if there is one. The SQL query would be like this (sticky to IDs for project and user to keep it readable): SELECT gp.project_id, gp.user_id , cp.title, cp.default_daily_rate, gc.daily_rate FROM projectassignment gp LEFT OUTER JOIN costprofile cp … -
Django Multi-Tenancy
How can i create a tenant_superuser in the schema which is not public? raise SchemaError(tenants.tenant_users.tenants.models.SchemaError:Schema must be public for UserProfileManager user creation I tried ./manage.py create_tenant_superuser --username=admin --schema=customer1 but got Schemaerror -
Django testing views - getting error - DiscoverRunner.run_tests() takes 2 positional arguments but 3 were given
I use Django framework to create basic web application. I started to write tests for my views. I followed the django documentation and fixed some issues along the way. But now I am stuck - I don't know why I get this error even after 30 minutes of searching for answer. C:\Osobni\realityAuctionClient\venv\Scripts\python.exe "C:/Program Files/JetBrains/PyCharm 2022.3.3/plugins/python/helpers/pycharm/django_test_manage.py" test realityAuctionClientWeb.test_views.TestViews.test_start_view C:\Osobni\realityAuctionClient Testing started at 7:41 ... Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm\django_test_manage.py", line 168, in <module> utility.execute() File "C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm\django_test_manage.py", line 142, in execute _create_command().run_from_argv(self.argv) File "C:\Osobni\realityAuctionClient\venv\Lib\site-packages\django\core\management\commands\test.py", line 24, in run_from_argv super().run_from_argv(argv) File "C:\Osobni\realityAuctionClient\venv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Osobni\realityAuctionClient\venv\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm\django_test_manage.py", line 104, in handle failures = TestRunner(test_labels, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm\django_test_runner.py", line 254, in run_tests return DjangoTeamcityTestRunner(**options).run_tests(test_labels, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm\django_test_runner.py", line 156, in run_tests return super(DjangoTeamcityTestRunner, self).run_tests(test_labels, extra_tests, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: DiscoverRunner.run_tests() takes 2 positional arguments but 3 were given Process finished with exit code 1 Empty suite My tests.py looks like this: import django from django.test import TestCase from django.urls import reverse class TestViews(TestCase): def test_start_view(self): """ Test that the start view returns a 200 response and uses the … -
Django: how to add creator of model instance (custom user) in FK field by default?
My model, where I wanna add creator of instance in author field by default from django.db import models from users.models import CustomUser from django_ckeditor_5.fields import CKEditor5Field class News(models.Model): TYPE_CHOICES = ( ('N', 'Новость'), ('A', 'Статья'), ('R', 'Обзор'), ) title = models.CharField("Заголовок", max_length=128) text = CKEditor5Field('Текст', config_name='default') image = models.ImageField('Фото', blank=True, null=True) publication_date = models.DateTimeField("Дата публикации", auto_now_add=True) news_type = models.CharField(choices=TYPE_CHOICES, max_length=1) source = models.CharField("Ссылка на первоисточник", max_length=128) author = models.ForeignKey(CustomUser, models.CASCADE, verbose_name="Автор публикации") allowed = models.BooleanField("Разрешено к публикации") Custom user class CustomUser(AbstractUser): email = models.EmailField('адрес эл. почты', unique=True) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() tg_username = models.CharField(max_length=64, blank=True, null=True) name = models.CharField('имя пользователя', max_length=64, blank=True, null=True) update = models.DateTimeField(verbose_name='Дата обновления', auto_now=True) create = models.DateField(verbose_name='Дата создания', auto_now_add=True) def __str__(self): return self.email class Meta: ordering = ["create"] verbose_name_plural = 'Профиль пользователей' verbose_name = 'Профиль пользователя' I'm expecting something like that (it's just for example): author = models.ForeignKey(CustomUser, models.CASCADE, default=request.user, verbose_name="Автор публикации") -
Static files not loading using nginx, docker and django
I'm trying to load static files using nginx and gunicorn, it works when i go to http://0.0.0.0/static/css/base.css static hosted via nginx, but doesn't when i add django port http://0.0.0.0:8000/static/css/base.css static not found using django server these are the errors i get in my nginx container nginx_1 | 172.22.0.1 - - [04/Oct/2023:04:59:33 +0000] "GET /static/css/base.css HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36" "-" nginx_1 | 2023/10/04 04:59:34 [error] 8#8: *2 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.22.0.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "localhost", referrer: "http://localhost/static/css/base.css" nginx_1 | 172.22.0.1 - - [04/Oct/2023:04:59:34 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://localhost/static/css/base.css" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36" "-" This is all what I've tried, in conf.d i put container name as server_name and tried to add types to determine css files, but it didnt work settings.py STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' Dockerfile FROM python:3.10 ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONBUFFERED=1 \ POETRY_VERSION=1.4.2 \ POETRY_VIRTUALENVS_CREATE="false" RUN pip install "poetry==$POETRY_VERSION" WORKDIR /education_platform COPY pyproject.toml poetry.lock docker-entrypoint.sh ./ RUN poetry install --no-interaction --no-ansi --no-dev COPY . /education_platform EXPOSE 8000 RUN chmod +x wait-for-it.sh docker-compose.yaml version: '3' services: db: image: … -
While trying to open Django web socket is showing Chat socket closed unexpectedly error
Channel layer is communicating with Redis but when I try to open websocket_urlpatterns = [ url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer), ] it shows not found and Chat socket closed unexpectedly error views -
Django App Not Reflecting the Changes in Files
I have a droplet on Digitalocean that runs Django. Whenever I make any changes on urls.py or views.py, I need to reboot the server in order to apply those changes in production. Is there any alternative method? Like if I delete the content of pycache directory, will it work? I tried touch commands but that didn't work. -
Can i add debit card details to billibg information details on heroku?
I have not credit card and i want to deploy a django app but requires payment method verification and this can done only done by credit card payment method on heroku so what i can do? I trie to add details of my debit card but not works. I think that this works because so many peoples having no any credit card then what those peoples do? -
Creating a test Django environment from the existing production Django project
I've developed a Django project which is in production and used by a small team daily. Now I want to make some changes in UI, since there is no test environment, I tried creating a similar base and home page with different names for testing in production environment but it is throwing error in ajax url resolving, I don't want to create another set of ajax url for testing. Is there any better way to create a test environment to test the UI changes and copy the html and java script alone? (it is a single developer project I use github only when I push any big change) -
increase the waiting time for response from server before returning the server time error with django and kubernetes
I am using Kubernetes and Google Cloud to host my web application and was looking for a way to increase the time for waiting for the server response before returning the error Internal server error Sorry, there seems to be an error. Please try again soon. I tried to search for the Kubernetes objects but no result thank you -
Django single choice field with choice of programming language category and quantity of possible answers
I would like to create a single choice quiz in Django. The question creator must: the possibility to add as many answers' fields as possible with a plus + or arrows up-down be capable of marking solely one answer as correct. be capable of choosing of predestined programming language category like here in text question. [![Singlequestion][1]][1] Here is my code: models.py # models.py from django.db import models class Category(models.Model): language_name = models.CharField(max_length=100, unique=True, default='') def __str__(self): return self.language_name class SingleChoiceQuestion(models.Model): question_text = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.question_text class SingleChoiceOption(models.Model): question = models.ForeignKey(SingleChoiceQuestion, on_delete=models.CASCADE) option_text = models.CharField(max_length=255) is_correct = models.BooleanField(default=False) def __str__(self): return self.option_text forms.py # forms.py from django import forms from .models import SingleChoiceQuestion, SingleChoiceOption class SingleChoiceQuestionForm(forms.ModelForm): class Meta: model = SingleChoiceQuestion fields = ['question_text', 'category'] options_count = forms.IntegerField(min_value=2, max_value=4, label="Number of Options Anzahl der Optionen") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) options_count = self.initial.get('options_count', 2) for i in range(options_count): self.fields[f'option_{i + 1}'] = forms.CharField(max_length=255, required=True) self.fields['correct_option'] = forms.ChoiceField( choices=[(f'option_{i + 1}', f'Option {i + 1}') for i in range(options_count)], widget=forms.RadioSelect, required=True, label="Correct Option Richtige Option" ) views.py # views.py from django.shortcuts import render, redirect from django.views import View from .forms import SingleChoiceQuestionForm class CreateSingleChoiceQuestionView(View): template_name … -
Dynamically creating models in django to be used in a unit test
I am attempting to create a test model in a unit test so that I can test associated behavior. Django documentation and related questions here on SO, both indicate that I should use the isolate_apps utility function, that in theory should register a temporary app which holds my test model. Note that I'm on django v1.11. My test looks like this: from django.test.utils import isolate_apps from django.db import models from django.test import TestCase class MyTest(TestCase): @isolate_apps("app_label") def test_the_model(self): class TestModel(models.Model): field = models.CharField(max_length=10) I'm not even running any assertions because it fails before. Error stack trace /usr/local/lib/python3.7/site-packages/django/test/utils.py:381: in inner with self as context: /usr/local/lib/python3.7/site-packages/django/test/utils.py:353: in __enter__ return self.enable() /usr/local/lib/python3.7/site-packages/django/test/utils.py:878: in enable apps = Apps(self.installed_apps) /usr/local/lib/python3.7/site-packages/django/apps/registry.py:56: in __init__ self.populate(installed_apps) /usr/local/lib/python3.7/site-packages/django/apps/registry.py:85: in populate app_config = AppConfig.create(entry) /usr/local/lib/python3.7/site-packages/django/apps/config.py:94: in create module = import_module(entry) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
from django.template import Template will this command into conda give me a folder inside my main one?
from django.template import Template in my class we are trying to create a folder inside our main folder, but I have no idea how to it. will from django.template import Template give a new folder inside my main one? btw, we are using VS code and Anaconda as the powershell. I am hoping someone can help me understand how to create a folder using django through conda