Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why not usable rest_framework? Help me [closed]
enter image description here INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'rest_framework', 'app', ] What? I don't understande this moment. I just started rest framework. I don't know rest framework. Please! help me!! try import rest framework expecting import rest framework -
Can any one help me to solve this error in django [closed]
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: IP address mismatch, certificate is not valid for '74.125.24.108'. (_ssl.c:992) I use google email services to reset password. I'm using windows 10. -
Multithreaded undetected chromedriver issue
I currently coded a scrapping function that works in my django web app and is hosted on Heroku, the scrapping function works through Celery and uses Undetected_ChromeDriver. The main issue is that there seems to be a problem when running the driver through multithreaded code because the code acts this way : Let's say I have 2 urls to scrap, the code is set to scrap this way : results = [] # Create a ThreadPoolExecutor with 10 workers with ThreadPoolExecutor(max_workers=10) as executor: # Assign tasks to each worker using the executor.submit method futures = [executor.submit(scrape_website, website, info, product_name) for website, info in websites.items()] # Wait for all workers to complete their tasks and retrieve their results for future in as_completed(futures): results.extend(future.result()) return results The code is set to open drivers this way : def create_selenium_instance(): options = uc.ChromeOptions() options.binary_location = os.environ.get("GOOGLE_CHROME_BIN") options.add_argument('--headless=new') options.add_argument('--no-sandbox') options.add_argument("--disable-gpu") options.add_argument("--disable-dev-shm-usage") options.add_argument("--disable-background-networking") options.add_argument("--disable-background-timer-throttling") options.add_argument("--disable-renderer-backgrounding") options.add_argument("--disable-sync") options.add_argument("--metrics-recording-only") options.add_argument("--disable-default-apps") options.add_argument("--mute-audio") options.add_argument("--no-first-run") options.add_argument("--disable-breakpad") chromedriver_path = os.environ.get("CHROMEDRIVER_PATH") renamed_path = "/app/.local/share/undetected_chromedriver/undetected_chromedriver" driver = uc.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), options=options) return driver The code is able to open the first URL and retrieve the correct informations (they get printed out in the logs) but as soon as it tries to open the second URL i … -
nginx host not found in upstream backend - docker
I'm trying to create docker container with nginx, frontend and backend. Frontend is react application and backend is a django application. Here is the docker-compose file version: '3' services: frontend: build: context: ./frontend dockerfile: Dockerfile.prod volumes: - frontend-data:/usr/share/nginx/html backend: build: context: . dockerfile: Dockerfile.prod environment: - DEBUG=0 - ALLOWED_HOSTS=nginx,localhost,127.0.0.1 - SECRET_KEY=django-Super-secret-key - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - static_data:/vol/web depends_on: - db networks: - app-networks db: image: postgres:latest restart: always environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - db-data:/var/lib/postgresql/data nginx: build: context: ./nginx dockerfile: Dockerfile.prod ports: - "80:80" volumes: - frontend-data:/usr/share/nginx/html/frontend - static_data:/vol/static depends_on: - frontend - backend networks: - app-networks networks: app-networks: driver: bridge volumes: db-data: frontend-data: static_data: in frontend Dockerfile I have moved the build files to volume and mounted it in nginx. I'm facing an error [emerg] 1#1: host not found in upstream "backend:8000" in /etc/nginx/nginx.conf:11 nginx: [emerg] host not found in upstream "backend:8000" in /etc/nginx/nginx.conf:11 Where my nginx.conf file is worker_processes 1; events { worker_connections 1024; } http { sendfile on; large_client_header_buffers 4 32k; upstream backend_servers { server backend:8000; } server { listen 80; server_name mysite.com; location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name mysite.com; ssl_certificate /etc/ssl/certs/my-site.crt; ssl_certificate_key … -
MIME type ('text/html') is not executable, and strict MIME type checking is enabled in DJANGO PYTHON
So I have a Django Projects, the localhost server is running, but there are few things missing in the frontend and it throws error like this: Refused to apply style from 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js' because its MIME type ('application/javascript') is not a supported stylesheet MIME type, and strict MIME checking is enabled. 127.0.0.1/:1 GET http://127.0.0.1:8000/... net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:45 Refused to execute script from 'http://127.0.0.1:8000/...' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. 127.0.0.1/:1 I think the error is in the navbar component because the div with class "nav_list" isn't showing. nav.html <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <link rel="stylesheet" href="/static/css/nav.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" > <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" ></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script> </head> <body id="body-pd"> {% if user.is_authenticated%} <header class="header" id="header"> <div class="header_toggle"> <i class='bx bx-menu' id="header-toggle"></i> </div> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false"> {{user}} </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1"> <li><a class="dropdown-item" href="{%url 'logout'%}">Logout<i class='bx bx-arrow-from-left bx-flip-vertical nav_logo-icon' style="float: right"></i></a></li> </ul> </div> </header> <div class="l-navbar" id="nav-bar"> <nav class="nav"> <div> <a href="#" … -
Data Structure Serialization (Django)
Good day. Tell me how can I convert and process the data received by the API into one model (one database table). The structure is like this: { "id": 1234567, "name": "Another Name", "price": 0, "responsible_user_id": 123456, "custom_fields_values": [ { "field_id": 500047, "field_name": "Gender", "field_code": null, "field_type": "select", "values": [ { "value": "Male", "enum_id": 267077, "enum_code": null } ] } ] } The object has dynamically added fields (custom fields), can I not create a separate model for custom fields, but bind them in some way to the main model and how can I process the data for saving? class Lead(models.Model): ... -
Is there anyway to deploy 2 django projects using docker having different domain?
I am new to programming world, so basically an average. Since few days, I am beating myself up in order to deploy 2 django projects having different domains with docker, uwsgi and Nginx but somehow I could not. Problem 1: I cant run 2nd nginx docker using port 80. Getting an error of port already in use. Problem 2: If I change the ports and run the app docker and nginx. It doesnt work. Both the domains pointing to Nginx at port 80. As per nginx logs. Problem 3: One domain that is mentioned in allowed hosts of django settings, works fine. And other domain throws a bad request error. Same thing on Vice-versa. I have read multiple articles saw multiple posts and videos still no help. So Ends up deploying the projects directly on the server using nginx and uswgi. I like the docker technology but had to stop it. There's not much relevant topics available in internet. So asking here with minimum to no hope. Am I missing something? Any points and help relevant to this topic would be appreciated? Thanks in advance -
Passing order to through paypal checkout
I have a django app and I am trying to create and Order through paypals checkout. I keep getting an error: "Uncaught Error: Expected an order id to be passed" My order and shipping address are been successfully created on the back end but paypal isnt seeming to accept it. I have tried many things to try and fix this. Hoping some one has some ideas: Here is my current script; paypal.Buttons({ // Order is created on the server and the order id is returned createOrder() { // Call the /get_cart_id/ endpoint to get the cart id return fetch("/get_cart_id/") .then((response) => response.json()) .then((data) => { const cartId = data.cart_id; return fetch("/api/orders/", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": csrftoken, }, body: JSON.stringify({ cart_id: cartId, }), }) .then((response) => response.json()) .then((order) => { orderId = order.id; // Set the orderId variable to the ID of the order return orderId; // Return the orderId to the caller }); }); }, // Finalize the transaction on the server after payer approval onApprove(data) { return fetch(`/api/orders/${orderId}/`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ order.id: data.orderID }) }) .then((response) => response.json()) .then((orderData) => { // Successful capture! For dev/demo purposes: console.log('Capture … -
How to apply Theme from ThemeRoller on JqGrid in Django framework
I'm developing my first Django app and I try to understand how to apply a ThemeRoller theme on my JqGrid. Where should I put the files after downloading the archive on https://jqueryui.com/themeroller/ ? My CSS and JS files are currently on the Static folder and everything is ok for me to access those files but i just don't know where to put the folder / files to get it to work... Thanks -
Http POST verb returns null value "realtor_id" violates not-null constraint when serializing data from model
I have been trying to serialize data from my real estate web-app but whenever i make http POST request to the backend it returns null value in column "realtor_id" violates not-null constraint. can someone help me resolve this issue. My model class Listing(models.Model): realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=100) state = models.CharField(max_length=100) zipcode = models.CharField(max_length=20) description = models.TextField(blank=True) price = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.DecimalField(max_digits=2, decimal_places=1) garage = models.IntegerField(default=0) sqft = models.IntegerField() lot_size = models.DecimalField(max_digits=5, decimal_places=1) photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) is_published = models.BooleanField(default=True) list_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title -
Django REST API Media URL Structure Problem
When I send a get request to a question with rest api in django. It looks like "image": "question_images/myphoto.png", But I also want the media folder to appear like "image": "media/question_images/myphoto.png", how can this be achieved? question_images located in the media folder. I configured MEDIA_URL. The Model. class Question(models.Model): TYPES_CHOICES = [ ("LAWYER","LAWYER"), ("REPAIRMAN","REPAIRMAN"), ] SITUATION_CHOICES = [ ("in","IN"), ("wait","WAIT"), ("closed","CLOSED") ] question_type = models.CharField(max_length=255,choices=TYPES_CHOICES,default="LAWYER") title = models.CharField(max_length=255) description = models.TextField() image = models.ImageField(upload_to="question_images/",blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) situation = models.CharField(max_length=20,choices=SITUATION_CHOICES,default="in") The Views.PY class QuestionViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticatedOrReadOnly] queryset = Question.objects.all() serializer_class = QuestionSerializer The Settings.py section STATIC_URL = "/static/" STATIC_ROOT = "/var/www/mydomainname/staticfiles" MEDIA_URL = "media/" MEDIA_ROOT = os.path.join(BASE_DIR,"media/") The Serializer class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ("user","id","title","description","image","created","updated","situation","question_type") def to_representation(self, instance): data = super(QuestionSerializer, self).to_representation(instance) data.pop("user") data.update({ "user":UserRepresentationSerializer(instance.user).data }) return data The Question URLS.PY router.register("question",views.QuestionViewSet,basename="questions") Whenever I make a request like api/questions/question/question_id it returns as "image": "question_images/logo.png", in the request section but i want like "image": "media/question_images/logo.png",. 127.0.0.1:8000/media/question_images/logo.png In addition, in the rest api part in settings.py, REST_FRAMEWORK = { 'UPLOADED_FILES_USE_URL': False, } when i remove this code it look like this. 127.0.0.1:8000/media/question_images/logo.png Yes, the media part is coming, but I want to remove the … -
Using Django TextChoices field in template if statements without hardcoding
Given a model like class Foo(models.Model): class FooTypes(models.TextChoices): OK = "F", "Ok" BAR = "B", "FooBared!" foo_type = models.CharField(max_length = 1, choices = FooTypes.choices) How can I use an IF statement in a template using FooTypes.OK or FooTypes.BAR (and not hard coding 'F' or 'OK' etc.). e.g. Something like {% if item.foo_type == FooTypes.OK %} ... {% endif %} -
"error: --plat-name must be one of ('win32', 'win-amd64', 'win-arm32', 'win-arm64')" with pip on venv while installing psycopg2
pip version: 23.1.1 Python version: 3.9.11 OS: Windows 11 My python project is created and env is used as virtual environment. psycopg2 fails to install. According to log, "Failed building wheel for psycopg2" and it also shows that the "The license_file parameter is deprecated". I have not found any solutions for my platform even though the solution exists for other platforms. Both wheel and setuptools are latest. pip install psycopg2-binary also does not work. The full error is below: (env) PS C:\\Aavash files\\COMP206\\Project\\Movie4AllMoods\> pip install psycopg2 Collecting psycopg2 Using cached psycopg2-2.9.6.tar.gz (383 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─\> \[34 lines of output\] C:\\Aavash files\\COMP206\\Project\\Movie4AllMoods\\env\\lib\\python3.9\\site-packages\\setuptools\\config\\setupcfg.py:293: \_DeprecatedConfig: Deprecated config in `setup.cfg` !! ******************************************************************************** The license_file parameter is deprecated, use license_files instead. By 2023-Oct-30, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://setuptools.pypa.io/en/latest/https://setuptools.pypa.io/en/latest/userguide/declarative_config.html for details. ******************************************************************************** !! parsed = self.parsers.get(option_name, lambda x: x)(value) running bdist_wheel running build running build_py creating build creating build\lib.mingw_x86_64-cpython-39 creating build\lib.mingw_x86_64-cpython-39\psycopg2 copying lib\errorcodes.py -> build\lib.mingw_x86_64-cpython-39\psycopg2 copying lib\errors.py -> build\lib.mingw_x86_64-cpython-39\psycopg2 copying … -
Django inlineFormset-factory can only update, not create. Create leads to error
For a recipe app I'm building I am working with an inline-formset-factory. I am doing this to learn to work with them and to better understand how they work. I have used this tutorial as an template. I've now started adjusting things to fit my use. I must have made a mistake somewhere as I now run into the following issue: I can update items just fine and without issue. I can't create new items as I get the following error: ManagementForm data is missing or has been tampered with. Missing fields: ingredients-TOTAL_FORMS, ingredients-INITIAL_FORMS. You may need to file a bug report if the issue persists. I don't understand where I made a mistake and would love some help to find and fix it. My view: class DrinkInline(): form_class = DrinkRecipeForm model = DrinkRecipe template_name = "products/product_create_or_update.html" def form_valid(self, form): named_formsets = self.get_named_formsets() if not all((x.is_valid() for x in named_formsets.values())): return self.render_to_response(self.get_context_data(form=form)) self.object = form.save() # for every formset, attempt to find a specific formset save function # otherwise, just save. for name, formset in named_formsets.items(): formset_save_func = getattr(self, 'formset_{0}_valid'.format(name), None) if formset_save_func is not None: formset_save_func(formset) else: formset.save() return redirect('products:list_products') def formset_ingredients_valid(self, formset): """ Hook for custom formset saving.Useful … -
How to apply language switch option to all pages? (Django project)
So I have this Django project that contains home page and a few other pages: My home page file looks like: {% load i18n %} <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <title>{% trans 'Blog' %}</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> </head> <body> <div class="g-image" style="background-image: linear-gradient( 112.1deg, rgba(32,38,57,1) 11.4%, rgba(63,76,119,1) 70.2% );"> <header> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="/">{% trans 'Blog' %}</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Navigation switch"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">{% trans 'Main' %}</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">{% trans 'About blog' %}</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {% trans 'Blog sections' %} </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="/pozn">{% trans 'Section1' %}</a></li> <li><a class="dropdown-item" href="/len">{% trans 'Не Section2' %}</a></li> <li> <hr class="dropdown-divider"> </li> <li><a class="dropdown-item" href="/superlren">{% trans 'Super section' %}</a></li> </ul> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {% trans 'language' %} </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown" class="g-image" style="background-image: linear-gradient( 112.1deg, rgba(32,38,57,1) 11.4%, rgba(63,76,119,1) 70.2% );"> <br> **<form action="{% url 'home' %}">> <textarea name="text1" cols="5" rows="1"></textarea><br/> <input type="submit" class='btn … -
Django dropdown list the browser does not see correctly
The main question why browser does not see all items the dropdown list? I want to have in navbar where Library button dropdown list that shows me All categories = "All" and the list of names of categories. File template base.html contains dropdown list: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>{% block title %}My shop{% endblock %}</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> </head> <body> <header> <nav class="navbar navbar-expand-md navbar-light bg-white border-bottom"> <div class="container-fluid"> <a class="navbar-brand" href="#">BookStore</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav me-auto mb-2 mb-md-0"> <li class="nav-item active"> <a class="nav-link" aria-current="page" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Library </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="{% url 'store:all_products' %}">All</a></li> {% for c in categories %} <li {% if category.slug == c.slug %}class="selected" {% endif %}> <a class="dropdown-item" href="{{ c.get_absolute_url }}">{{ c.name|title }}</a> </li> {% endfor %} </ul> </li> </ul> <form class="d-flex"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> </header> <div id="content">{% block content %} {% endblock … -
Django Views.Py Create Filter
I tried to create a question filtering function using my model below. In the filtering I want, I want it to be filtered by the values of question_type and situation. If two values are sent at the same time, I want filtering by two values. If single value is sent I want it to be filtered by single value. The Model class Question(models.Model): TYPES_CHOICES = [ ("LAWYER","LAWYER"), ("REPAIRMAN","REPAIRMAN"), ] SITUATION_CHOICES = [ ("in","IN"), ("wait","WAIT"), ("closed","CLOSED") ] question_type = models.CharField(max_length=255,choices=TYPES_CHOICES,default="LAWYER") title = models.CharField(max_length=255) description = models.TextField() image = models.ImageField(upload_to="question_images/",blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) situation = models.CharField(max_length=20,choices=SITUATION_CHOICES,default="in") I tried this function but it didn't work. I provide submission by rest api. class TypeView(ListAPIView): serializer_class = QuestionSerializer def get_queryset(self): qs = Question.objects.all() question_type = self.request.query_params.get('question_type') situation = self.request.query_params.get('situation') if question_type and situation: qs = qs.filter(question_type=question_type, situation=situation) elif question_type: qs = qs.filter(question_type=question_type) elif situation: qs = qs.filter(situation=situation) return qs The urls.py path path('search/<str:question_type>/<str:situation>/', views.TypeView.as_view(), name='filtered-question'), -
Self-subscription Test
test_views enter image description here The self-subscription test doesn't work models enter image description here views enter image description here Honestly I don't know why it doesn 't work (I have little experience writing code ) -
How to create related one-to-one object simultaneously when creating parent object in Django?
I have a User model that extend AbstractUser model inside an app that is called core. I use this model as AUTH_USER_MODEL in settings.py. I also have UserProfile model which has a one-to-one relationship with User My goal is to create a UserProfile whenever a new User is created simultaneously. # file name: core/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(unique=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) The problem: When I use shell to create a new user I get this error: >>> bob = User.objects.create_user(email="bob@outlook.com", username="bob") TypeError: int() argument must be a string, a bytes-like object or a real number, not 'ModelBase' The above exception was the direct cause of the following exception: TypeError: Field 'id' expected a number but got <class 'core.models.User'>. During handling of the above exception, another exception occurred: ValueError: Cannot assign "<class 'core.models.User'>": "UserProfile.user" must be a "User" instance. >>> How should I solve this error? To create UserProfile whenever a new User is created I use signals as shown below: # file name: core/signals.py from django.db.models.signals import post_save from django.dispatch import receiver from core.models import User, UserProfile @receiver(post_save, sender=User) def create_userprofile(sender, **kwargs): try: UserProfile.objects.get(user=sender) except Exception: sender.userprofile … -
AWS SES: AccessDenied when calling SendRawEmail - User is not authorised to perform ses:SendRawEmail on Resource
Alright, this is the moment I'm completely freaking out. And it is probably something small I'm missing out on, but I'm stuck for almost 2 days at the moment. I'm trying to send an email via SES, I'm already out of sandbox mode. Whenever I log in on AWS and try to send an email via the 'Send test Email' button, everything works fine. If I use Boto3/django-ses library, I get the Permission Denied error, same user, a different way of performing the action. The user has the following policies attached: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "*", "Resource": "*" } ] } & (because I got trust issues) { "Statement": [ { "Action": [ "ses:SendEmail", "ses:SendRawEmail" ], "Effect": "Allow", "Resource": "*" } ], "Version": "2012-10-17" } && Because I got even more trust issues I also attached an Authorization policy to the SES verified identity: { "Version": "2012-10-17", "Statement": [ { "Sid": "stmt1682154101077", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::FOO:user/BAR" }, "Action": [ "ses:SendEmail", "ses:SendRawEmail" ], "Resource": "arn:aws:ses:eu-central-1:FOO:identity/no-reply@example.com", "Condition": {} } ] } Which part am I missing to give the user permission to send email not via the AWS Console but via the Library? -
Django deployment failed on railway
does anyone know how to fix this build error https://i.stack.imgur.com/eNOpR.png I am trying to deploy my MEAN stack backend on Railway from GitHub repo, but I get a Nixpacks error -
django redirect when in HttpStreamingResponse
i am developing a django application, which scans the barcodes from camera feed using pyzbar and displays the data def scan_barcode(request): return StreamingHttpResponse( scan_feed(), content_type="multipart/x-mixed-replace; boundary=frame" ) this is view i am using to view my camera feed def scan_feed(): global qr_data while True: frame, qr_data = scanner(camera) if qr_data: print(qr_data) print("redirecting....") return redirect("/profile") yield (b"--frame\r\n" b"Content-Type: image/jpeg\r\n\r\n" + frame + b"\r\n\r\n") this is scan_feed function where i am validating the qrdata and wants to redirect to another page <img src="http://localhost:8000/scan_barcode"> this is the html code i am accesing the camera feed, i can see the camera feed and recognise the qrcode and printing it successfully but unable to redirect to next page any suggestions on above code PS: i am new to Django Framework Thanks in advance -
Reverse for 'None' not found. 'None' is not a valid view function or pattern name
I wan multilanguage webpage. it works fine with when I manually enter language abbreviation. For example, www.my_page.com/en but when adding in HMTL with a link it throws an error. Couldn't figure out what is the problem. Here is the code. view function in my app def store(request): return render(request, "store/store.html") def set_language(request, language): for lang, _ in settings.LANGUAGES: translation.activate(lang) try: view = resolve(urlparse(request.META.get("HTTP_REFERER")).path) except Resolver404: view = None if view: break if view: translation.activate(language) next_url = reverse(view.url_name, args=view.args, kwargs=view.kwargs) response = HttpResponseRedirect(next_url) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language) else: response = HttpResponseRedirect("/") return response app url.py urlpatterns = [ path("", views.store, name="store"), path("set_language/<str:language>/", views.set_language, name="set-language"), ] project url.py urlpatterns = [ path('admin/', admin.site.urls), path("", include("store.urls")), ] urlpatterns = [ *i18n_patterns(*urlpatterns, prefix_default_language=False), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my template html file <!-- Topbar Start --> <div class="container-fluid bg-dark text-light px-0 py-2"> <div class="row gx-0 d-none d-lg-flex"> <div class="col-lg-5 px-5 text-end"> <i class="fa fa-globe"></i> <span>Language:</span> <a href="{% url 'set-language' 'tm' %}">TKM</a> <a href="{% url 'set-language' 'ru' %}">RU</a> <a href="{% url 'set-language' 'en' %}">ENG</a> <a href="{% url 'set-language' 'tr' %}">TR</a> </div> </div> </div> <!-- Topbar End --> i tried multilanguage function in root level. It works fine but with application it goes like this NoReverseMatch at /set_language/en/ … -
Django uploading an image - class based view
i want to save a model(Villa) in django with this form everغthing is ok but i don't know how to upload images with that when the villa is saved, it gets all its information, but saves the photos in a fake path that doesn't exist is there anyway to upload the image دn this method ?? it's the code HTML {% extends 'base.html' %} {% load static %} {% block title %}Save Villa{% endblock title %} {% block content %} <script src="{% static 'assets/villa_save_form_check.js' %}"></script> <script src="{% static 'assets/villa_save_handle.js' %}"></script> <div class="container my-5 rounded-3 w-100 h-100 justify-content-center d-flex"> <div class="row"> <div class="col-12"> <form method="POST" class="form-control"> <h1 class="form-label">Villa</h1> <hr> <input type="hidden" name="username" id="username" class="form-control" value="{{user.username}}"> <label class="form-label mt-1">Full Name</label> <input type="text" name="owner_id" id="owner_id" placeholder="Owner Name" class="form-control mb-2" required> <label class="form-label mt-1">Phone Number</label> <input type="number" oninput="phoneCheck()" name="phone_id" id="phone_id" placeholder="Owner Phone Number" class="form-control mb-2" required> <label class="form-label mt-1">Price</label> <input type="number" name="price_id" id="price_id" oninput="priceCheck()" placeholder="Villa Price" class="form-control mb-2" required> <label class="form-label mt-1">Address</label> <input type="url" name="address_id" id="address_id" placeholder="Villa Address" class="form-control mb-2" required> <label class="form-label mt-1">About</label> <textarea name="description_id" id="description_id" oninput="descriptionCheck()" class="form-control mb-2" cols="100" rows="5" placeholder="Description" required></textarea> <label class="form-label mt-1">Title Image</label> <input type="file" name="title_id" id="title_id" placeholder="Villa Address" class="form-control mb-2" required> <label class="form-label mt-1">Image 1</label> <input type="file" name="img1_id" … -
Getting Similarly-Named Keys from Redis Cache on Django web app
I am currently having trouble trying to cache a large Pandas DataFrame (300,000+ rows) that has 3 columns, an ID column and 2 large numpy array columns. I am unable to cache the whole DataFrame as one object since it is so large. So, I thought to cache by number, break up the DataFrame, and load them back in as chunks. The number of rows in the DataFrame increase daily, so I will never know how many chunks of rows are cached. Therefore, I save them as 'encodings_df_1', 'encodings_df_2', ..., 'encodings_df_n'; where n is the highest number needed to cache all chunks of the original DataFrame. Is there a way to get all the keys where it is like 'encodings_df_*', or is there an easier way to cache and load the original DataFrame back in? EXAMPLE: # Let's say the Pandas DataFrame 'df' currently has a length of 350 #I should have 4 objects cached in my Redis db: # encodings_df_1, encodings_df_2, encodings_df_3, and encodings_df_4 # initial vars chunk_size = 100 number_of_chunks = math.ceil(len(df) / chunk_size) # upper and lower bounds for DF segmentation lower = 0 upper = lower + chunk_size # loop to cache DF chunks for n …