Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert C++ PPL task<t> into .NET TPL Task<T>, using C++/CLI
I have a .NET interface which returns asynchronous Task objects. public interface MyInterface { public Task<void> DoTheThing(); } For Special Reasons, suppose I wanted to implement this interface using native code, compiled in C++/CLI. It's my understanding that Visual Studio 17.6 recently introduced support for C++20 with coroutines, in CLI-enabled compilation units. Our native code uses PPL task<T> templates with co_awaitc to achieve the same asynchronous approach that C#'s async/await keywords do with Task<T> objects. What options are available, for 'converting' (or wrapping) a native function which returns a PPL task<T>, into a managed Task<T>? -
How did |= change its behavior? [duplicate]
I just tracked down a bug in some C++ code, and it came down to a behavioral change in a C++ operation. I am just curious what caused the behavior change, was it a C++ standards change, or a hardware platform change? Also roasting me that I should have known better because of this reason or that etc are welcome. :-P This code: long sam = 0; sam |= ((char)-1); std::cout << "sam became " << sam << std::endl; On my Raspberry PI with gcc 8.3.0 that outputs 255. On my AMD Ryzen Threadripper with gcc 9.4.0 that outputs -1. -
Template compilation should fail but as long as offending function is not used, compilation succeeds
I would expect the code below to fail to compile because of the member function f of Exclamator<B> as B does not provide required name member. In reality it compiles fine when f is not used, even with optimizations turned off. How is this possible? #include <string> #include <iostream> class A { public: std::string name() { return "A"; } }; class B {} ; template <typename T> class Exclamator { public: Exclamator(T a): x{a} {} void f() { std::cout << x.name() << std::endl; } private: T x; }; int main() { A a; Exclamator xa {a}; xa.f(); B b; Exclamator xb {b}; // xb.f(); return 0; } $ g++ -std=c++17 -O0 main.cpp $ ./a.out A -
python django - How to make my projrct work on vercel.com
I log in to my vercel account and use github(project site https://github.com/TomTomThomas780/learning-log) and make it on vercel. But it is always a 404 and I don't know why. Website: learning-log-tau.vercel.app. The project works on localhost. My packages version is in requirements.txt -
Write access violation allocating memory for nested data structure on GPU using CUDA C/C++
I have the following data structure: typedef struct { float var1; signed short var2; float var3[4]; float var4[3]; float var5[3]; float var6; } B; typedef struct { signed long num_objects; signed long max_objects; B* objects; } A; I would like to allocate memory for data structure A and its element B* objects. I am doing it in the following way: A* deviceOutputData = nullptr; B* deviceOutputDataObject = nullptr; cudaDeviceSynchronize(); cudaError_t cudaStatus = cudaMalloc(&deviceOutputData, sizeof(A)); cudaDeviceSynchronize(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc for deviceOutputData failed: %s\n", cudaGetErrorString(cudaStatus)); } cudaDeviceSynchronize(); cudaStatus = cudaMalloc(&deviceOutputDataObject, sizeof(B) * max_objectsA); cudaDeviceSynchronize(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc for deviceOutputDataObject failed: %s\n", cudaGetErrorString(cudaStatus)); cudaFree(deviceOutputData); } else { cudaDeviceSynchronize(); deviceOutputData->objects = deviceOutputDataObject; } But I am getting write access violation when I do deviceOutputData->objects = deviceOutputDataObject; Can anyone help me solve this issue? I have tried the above code and I am expecting to successfully allocate memory for both A and B and link B address with A address of the data structure. -
Get class name which has an attribute in gdb
In gdb is it possible to know the name of the class that has a certain attribute? Here is an example: class A { public: int my_val; }; class B: public A { public: int my_other_val; }; class C: public B { public: int my_other_other_val; }; int main(int argc, char* argv[]) { C obj1; obj1.my_val = 10; } From obj1 can I know the name of the class with has the attribute my_val? -
unable to compile opengl program inside docker container
I want to compile and run an opengl program inside docker container. For this I used this https://github.com/atinfinity/cudagl Creating docker image and run works fine. glxgears shows the gears in a window. I also installed libglew-dev inside docker container with sudo apt-get install libglew-dev But when I want to compile my program I get this error: square.cpp:(.text+0xe): undefined reference to `glMatrixMode' /usr/bin/ld: square.cpp:(.text+0x13): undefined reference to `glLoadIdentity' /usr/bin/ld: square.cpp:(.text+0x32): undefined reference to `glClearColor' /usr/bin/ld: /tmp/ccSFc4Tx.o: in function `Update(GLFWwindow*)': square.cpp:(.text+0x60): undefined reference to `glfwSetWindowShouldClose' /usr/bin/ld: /tmp/ccSFc4Tx.o: in function `RenderScene(GLFWwindow*)': square.cpp:(.text+0xd1): undefined reference to `glClear' /usr/bin/ld: square.cpp:(.text+0xf0): undefined reference to `glColor3f' /usr/bin/ld: square.cpp:(.text+0x119): undefined reference to `glScalef' /usr/bin/ld: square.cpp:(.text+0x176): undefined reference to `glBegin' /usr/bin/ld: square.cpp:(.text+0x1a3): undefined reference to `glVertex2f' /usr/bin/ld: square.cpp:(.text+0x1c8): undefined reference to `glVertex2f' /usr/bin/ld: square.cpp:(.text+0x1f5): undefined reference to `glVertex2f' /usr/bin/ld: square.cpp:(.text+0x1fa): undefined reference to `glEnd' /usr/bin/ld: square.cpp:(.text+0x1ff): undefined reference to `glFlush' /usr/bin/ld: /tmp/ccSFc4Tx.o: in function `main': square.cpp:(.text+0x250): undefined reference to `glfwInit' /usr/bin/ld: square.cpp:(.text+0x275): undefined reference to `glfwCreateWindow' /usr/bin/ld: square.cpp:(.text+0x285): undefined reference to `glfwMakeContextCurrent' /usr/bin/ld: square.cpp:(.text+0x294): undefined reference to `glfwWindowHint' /usr/bin/ld: square.cpp:(.text+0x2af): undefined reference to `glfwSetKeyCallback' /usr/bin/ld: square.cpp:(.text+0x2da): undefined reference to `glfwSetTime' /usr/bin/ld: square.cpp:(.text+0x2e6): undefined reference to `glfwSwapBuffers' /usr/bin/ld: square.cpp:(.text+0x2eb): undefined reference to `glfwPollEvents' /usr/bin/ld: square.cpp:(.text+0x2f7): undefined reference to `glfwWindowShouldClose' /usr/bin/ld: … -
suppress warning "left operand of comma operator has no effect" [duplicate]
In the following code, a array with repeated elements is created using a fold expression: #include <array> #include <utility> template <std::size_t N> class A { int m_x; public: static constexpr std::size_t size = N; A(int x) : m_x{x} { } int f() const noexcept { return m_x; } int g() const noexcept { return m_x * m_x; } }; template <typename U, std::size_t... I> auto get_array_impl(const U& m, std::index_sequence<I...>) { return std::array<int, m.size + 1>{ m.g(), (I, m.f())... }; } template <typename U, std::size_t... I> auto get_array(const U& m) { return get_array_impl(m, std::make_index_sequence<m.size>{}); } int main() { A<3> x{8}; auto a = get_array(x); return 0; } Check it live on Coliru. Compiling the code gives a warning: main.cpp:18:50: warning: left operand of comma operator has no effect [-Wunused-value] 18 | return std::array<int, m.size + 1>{ m.g(), (I, m.f())... }; While it's clear why the warning is created (I is practically discarded), it is also clear that this is not an issue, since the code does not really need the I-values, but rather uses the variadic expansion to repeat m.f(). How can I suppress the warning while still compiling with -Wall? Is there some variation of the syntax that gives the … -
Incredibuild add-in fails to build C++ solution in Visual Studio
I upgraded my older Incredibuild installation with the latest version 10.5 to fix an invalid license error on Windows and I also upgraded my Visual Studio 2022 add-in respectively since I'm working in Visual Studio on C++ projects. When I initiate a build with Incredibuild, I'm getting a failure the following output: --------------------Build System Warning--------------------------------------- Checking MSBuild version: Cannot load version info from: �l�R�ct Visual Studio Solution File, Format VersionMSBuild\Current\Bin\amd64\, Error: 123 ------------------------------------------------------------------------------- --------------------Build System Warning--------------------------------------- Visual Studio does not include an English language pack: This version of Visual Studio does not include a built-in English language pack. For the best Incredibuild experience, it is highly recommended to install a Visual Studio English language pack. ------------------------------------------------------------------------------- Build ID: {184494E3-2125-4767-B661-F6D0037AE45A} Active code page: 437 The filename, directory name, or volume label syntax is incorrect. 2 build system warning(s): - Checking MSBuild version - Visual Studio does not include an English language pack I verified my Visual Studio Installer language packs and I have English installed, my Visual Studio is in English after all so the warning seems bogus: Overall I don't understand why Incredibuild is failing, maybe it calls a bad command in the Visual Studio 2022 development tools which implies … -
Check return stament of c++ code in vscode [duplicate]
Is it possible to check the result in a return statement in vscode running gdb? Here is an example: bool foo(int i) { return i>10; } int main(int argc, char* argv[]) { foo(11); } When using vscode with gdb to debug this code, once I step over the line with return i>10; I will end up in the line with }. Can I extract what was evaluated in the return statement without leaving the function? -
Django server not accessible when run through docker-compose: connection reset by peer
I have a docker image which runs django. Docker-compose is like this: services: www: image: my-www-image ports: - "80:80" If I docker exec -ti bash into this container and curl localhost, I get Django-related output, and the docker-compose log notes the GET request. If I go to the host machine and curl localhost, I get curl: (56) Recv failure: Connection reset by peer (note this is not a Connection refused, which I would get if I use a random wrong port number) Adding EXPOSE 80 to the Dockerfile made no difference. Why can't the host machine connect to the otherwise-working service inside the container? -
Ajax form not passing Product Id and Product Title to cart
I'm following Zander from Very Academy Ecommerce tutorial series and reached the part where we use Ajax to submit form data of the product to the cart. I've managed to pass the quantity and the price but not the title. Its not rendering(displaying) in the cart page. Everything else works fine. I messaged Zander asking for help and its been a month and still no response from him. Here is the Ajax from the tutorial: <script> $(document).on('click', '#add_button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "inventory:single_product_add_to_cart" %}', data: { productid: $('#add_button').val(), productqty: $('#select option:selected').text(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post' }, success: function (json) { }, error: function (xhr, errmsg, err) {} }); }) </script> This is my product model: class Product(models.Model): product_metas_set = models.ForeignKey(ProductMetas, on_delete=models.CASCADE, related_name='product_metas') PRODUCT_TYPE = ( ('single_product','Single product'), ('variable_product','Variable product'), ('groupped_product','Groupped product'), ) PRODUCT_STATUS = ( ('is_inactive','Inactive'), ('is_active','Active'), ('published','Published'), ) product_status = models.CharField(choices=PRODUCT_STATUS, max_length=100) product_is_featured = models.BooleanField(default=False) product_is_bestseller = models.BooleanField(default=False) product_is_on_sale = models.BooleanField(default=False) high_sell_through = models.BooleanField(default=False) price_regular = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) price_sale = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) product_UPC = models.CharField(max_length=300, blank=True, null=True) product_SKU = models.CharField(max_length=300, blank=True, null=True) product_MODEL_ID = models.CharField(max_length=300, blank=True, null=True) product_stock_management = models.ForeignKey(ProductStockManagement, on_delete=models.CASCADE, related_name='product_stock_management') product_attributes_set = models.ForeignKey(ProductAttributesSets, on_delete=models.CASCADE, related_name='product_attributes_set') product_specifications_set = … -
Add offset to a time
I have a string that I convert to time based on certain format const std::string format = "%Y-%m-%dT%H:%M:%S"; std::istringstream dateStream(date); std::tm tm = {}; dateStream >> std::get_time(&tm, format.c_str()); Then I want to add an offset to it and print the result as a string: tm.tm_min += offset; std::mktime(&tm); std::ostringstream resultStream; resultStream << std::put_time(&tm, format.c_str()); It seems to work here https://godbolt.org/z/q7svh51Y7 But when I run it on my local system I receive 2023-09-26T18:18:23 instead of 2023-09-26T17:18:23 Could you help with a solution for this ? -
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