Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why can't I output the full values using get_foo_display?
There is a Django form. When I send a GET-request, I output a new empty form, when I click "Submit", I display on the page what the user entered in the questionnaire. The problem is that I want some data to be output not as an internal representation, but as an full one (idk how it called correctly). I'm a beginner in Django and may not understand many nuances. I tried to add data to the dictionary individually, but it didn't lead to anything. pool.html: <p><b>Ваше имя:</b> {{ form_data.name }}</p> <p><b>Ваш пол:</b> {{ form_data.get_sex_display }}</p> forms.py: class FeedbackForm(forms.Form): SEX_OPTIONS = ( ('m', 'Мужской'), ('f', 'Женский'), ('none', 'Паркетный') ... sex = forms.ChoiceField( widget=forms.RadioSelect, choices=SEX_OPTIONS, label='Ваш пол:' ) views.py: def pool(request): assert isinstance(request, HttpRequest) context['title'] = 'Обратная связь' if request.method == 'GET': form = FeedbackForm() else: form = FeedbackForm(request.POST) if form.is_valid(): form_data = request.POST.dict() context['form_data'] = form_data context['form'] = form return render(request, 'app/pool.html', context=context) -
Django changes the MEDIA URL if I pass request from views to serializer
I am working on a Social Media project. I successfully implemented image upload and now working on Like model which allows users to like a post. At present state, if a user clicks on Like button, it turns red. All I want is if the page reloads or the same user logins again, the specific post's like button must remain red. In order to achieve so, I am trying to add extra field in serializer(below): liked_by_current_user with which I can filter out as to when the like color must be red. (The REST APIs are working correctly) models.py: class Comment(models.Model): text = models.TextField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=100, blank=True) profile_image = models.ImageField(upload_to='user_image', null=True, blank=True) class Like(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) selected views.py def feed(request): context = { 'MEDIA_URL': settings.MEDIA_URL, # pass MEDIA_URL to the template } return render(request, 'post_list_temp.html', context) class PostListView(APIView): def get(self, request, *args, **kwargs): posts = Post.objects.filter(deleted=False).order_by('-created_on') context = { 'post_list' : posts, } paginator = defPagination() result = paginator.paginate_queryset(posts, request, view=self) serializer = feedSerializer(result, context={"request":request}, many=True) return paginator.get_paginated_response(serializer.data) def post(self, request, *args, **kwargs): if request.user.is_authenticated: print(request) serializer … -
TimescaleDB: Image does not recognize created hypertables
I am running a django app with timescaledb as local DB image. It was working until recently (maybe 2 days ago). Now I get the following error: ERROR: function create_hypertable(unknown, unknown, chunk_time_interval => interval) does not exist at character 8 HINT: No function matches the given name and argument types. You might need to add explicit type casts. Answers to other questions (e.g: TimescaleDB: Is it possible to call 'create_hypertable' from Python?) regarding this topic suggest to install the timescaledb extension. But I am running the timescaledb-ha image which comes with the extension included (https://hub.docker.com/r/timescaledev/timescaledb-ha). I also tried to create the hypertables with if_not_exists => TRUE as suggested here: https://github.com/timescale/timescaledb/issues/189. I assume there is a bug in the image since it was updated 2 days ago and before it was working. Parts of my dockerfile: postgres: container_name: postgres_postgis image: timescale/timescaledb-ha:pg14 volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres Can somebody help? Would be highly appreciated. Thanks in advance -
Converting multiple left join SQL into a django ORM query
I am having trouble creating a corresponding django ORM query for the following SQL Join: select su.user_id from slack_slackuser as su left join auth_user as au on su.user_id = au.id left join core_profile as cp on au.id = cp.user_id where cp.org_id = 8; Here slack_slackuser maps to SlackUser django model, auth_user maps to the django's AUTH_USER_MODEL and core_profile maps to Profile model. This is what I was trying to do, but this fails.: SlackUser.objects.filter(user_id__core_profile__org_id=org.id).values_list('user_id', flat=True) -
Taking three records from the products in the table according to their categories
I have two tables named categories and products. How can I get three records from each category on the homepage? Thanks in advance class Category(models.Model): name = ... class Produc(models.Model): name = ... category = models.ForeignKey(Category, ... class Home_Cls(TemplateView): ... def homepro(self): cats = Category.objects.all() for cat in cats : que= Products.objects.filter( category_id=cat[..] ).order_by('?')[:3] return que I tried a little. :( Waiting for your help. -
Nginx doesn't see or use subdomain config
Problem: nginx doesn't apply configuration for subdomain if there are domain and subdomain config at the same time. Disclaimer: I'm new to nginx and server deployment. Question: What I do wrong with nginx configuration? Additional info: Nginx 1.18.0 Ubuntu 20.04 Details: I have main domain (it's my portfolio) (let's say example.com) and subdomain (todo-tracker.example.com). Both are django projects started with gunicorn (main on 127.0.0.1:8000, todo-tracker on 127.0.0.1:8001). I have two sites-available config files: default - for main domain server { server_name example.com; location / { proxy_pass http://127.0.0.1:8000/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /static { autoindex on; alias /home/portfolio/portfolio/staticfiles; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; listen [::]:80 ipv6only=on; server_name example.com; return 404; # managed by Certbot } todo-tracker - for subdomain server { server_name todo-tracker.example.com; location / { proxy_pass http://127.0.0.1:8001/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header … -
Database error "Access denied for user 'admin'@'localhost' (using password: YES)")
While working on my first Django project, I am trying to connect my application to MySQL database and it keeps giving me this error. I have installed mysqlclient. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'minesupdb', 'USER': 'admin', 'PASSWORD': 'my_password', 'HOST': 'localhost', -
DJango allauth Microsoft Graph
I have a DJango program called 'p_verison1'. Then I have a second application to manage users called "users". There I have implemented login and it works fine. I have added that you can login with Microsoft using "allauth". The problem is that after pressing the "sign in with microsoft" button, instead of taking you directly to the page to choose the microsoft account, it first takes you to a second page where you have to click on the continue button. I want to remove that second page, I want it to always take as the user clicks the button and continue and directly take you to the Microsoft page. I've been trying different ways but I can't remove the second page. My "login.html": <div class="form-group"> <div class="socialaccount_providers" style="margin=0px"> {% include "socialaccount/snippets/provider_list.html" with providers="microsoft" process="login" %} </div> </div> My "provider_list.html" {% load socialaccount %} {% load static %} {% get_providers as socialaccount_providers %} {% for provider in socialaccount_providers %} {% if provider.id == "openid" %} {% for brand in provider.get_brands %} <div> <a title="{{brand.name}}" class="socialaccount_provider {{provider.id}} {{brand.id}}" href="{% provider_login_url provider.id openid=brand.openid_url process=process %}" >{{brand.name}}</a> </div> {% endfor %} {% endif %} <div class="my-2"> <a title="{{provider.name}}" class="socialaccount_provider {{provider.id}}" href="{% provider_login_url provider.id process=process … -
At Console : Uncaught TypeError: $.get is not a function
i am writing a django application, and using autocomplete this is my home.html file where i am trying to load the jquery files {% block home_css %} <link rel="stylesheet" type="text/css" href="{% static 'home.css' %}"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet"> <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script> <script type="text/javascript" src="{% static 'autocomplete.js' %}"></script> {% endblock %} and this is my autocomplete.js file var $ = jQuery.noConflict(); $(document).ready(function() { $('#ticker').on('input', function() { var input = $(this).val(); if (input.length >= 3) { $.get('https://www.alphavantage.co/query', { function: 'SYMBOL_SEARCH', keywords: input, apikey: 'my_api_key' //i have uploaded my key in my local code }, function(response) { $('#autocomplete').empty(); for (var i = 0; i < 5 && i < response.bestMatches.length; i++) { $('#autocomplete').append('<div class="autocomplete-suggestion">' + response.bestMatches[i]['1. symbol'] + '</div>'); } $('.autocomplete-suggestion').on('click', function() { var symbol = $(this).text(); $('#ticker').val(symbol); $('#autocomplete').empty(); }); }); } else { $('#autocomplete').empty(); } }); }); and i don't know if this is necessary to upload, but i am extending base.html in my home.html <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'base.css' %}"> <title>GrittyGains</title> {% block home_css %} {% endblock %} </head> i have tried rearranging files as some solution showed … -
Django docker - template does not exists but admin page loads
im dockerizing my app. App builds and runs, but when i try to access some base URL like /login I get TemplateDoesNotExist at /login/ However when I'm accessing my REST, ADMIN, SWAGGER I can see everything properly so I think the problem is on my side. Here is the dockerfile from python:3.11-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /basicapp COPY requirements.txt requirements.txt RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD python manage.py runserver 0.0.0.0:8000 here is docker-compose version: "3.11" services: app: build: . volumes: - .:/basicapp ports: - 8000:8000 image: app:django container_name: basic_container command: python manage.py runserver 0.0.0.0:8000 Here is my template settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] and the app structure is simple core <-settings etc app templates static -
AssertionError: The field 'uploaded_file' was declared on serializer LessonPlanNotesSerializer, but has not been included in the 'fields' option
My Models class LessonPlan(models.Model): planner=models.ForeignKey('LessonPlanner', on_delete=models.CASCADE) title=models.CharField(max_length=100, null=True, blank=True) details=models.TextField(null=True, blank=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class LessonStudyMaterial(models.Model): Lesson=models.ForeignKey('LessonPlan', on_delete=models.CASCADE) file=models.FileField(upload_to=get_upload_path, null=True, blank=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) My Serializer class LessonPlanSerializer(serializers.ModelSerializer): uploaded_file=serializers.ListField(child=serializers.FileField(max_length=2000) class Meta: model = LessonPlan fields=['id', 'planner', 'title', 'details', 'uploaded_file',] My post request contains title, details, and multiple files that will post in the child model LessonStudyMaterial so I have added the uploaded_file field to validate data while posting but it showing an error -
we are using postman and swagger for JWT authorization to authorize token ... is it possible in drf UI for authorization of JWT token?
We are using postman and swagger for authenticating and authorizing the JWT authentication we are logging in and we are getting both access token and refresh token and we are placing this access token in swagger/postman as bearer token and authorizing.. Is it possible in DRF UI for authorizing token and accessing the API's Expecting JWT Authorizing and accessing all the API's in DRF UI instead of swagger and Postman -
AttributeError: module 'logging' has no attribute 'getLogger' when creating a new environment
I was trying to create a new virtual environment using python. but when I executed the command python3 -m venv env It shows the following error. Traceback (most recent call last): File "/usr/lib/python3.8/runpy.py", line 185, in _run_module_as_main mod_name, mod_spec, code = _get_module_details(mod_name, _Error) File "/usr/lib/python3.8/runpy.py", line 144, in _get_module_details return _get_module_details(pkg_main_name, error) File "/usr/lib/python3.8/runpy.py", line 111, in _get_module_details __import__(pkg_name) File "/usr/lib/python3.8/venv/__init__.py", line 15, in <module> logger = logging.getLogger(__name__) AttributeError: module 'logging' has no attribute 'getLogger' Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 72, in apport_excepthook from apport.fileutils import likely_packaged, get_recent_crashes File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module> from apport.report import Report File "/usr/lib/python3/dist-packages/apport/report.py", line 32, in <module> import apport.fileutils File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 12, in <module> import os, glob, subprocess, os.path, time, pwd, sys, requests_unixsocket File "/usr/lib/python3/dist-packages/requests_unixsocket/__init__.py", line 1, in <module> import requests File "/usr/lib/python3/dist-packages/requests/__init__.py", line 43, in <module> import urllib3 File "/usr/lib/python3/dist-packages/urllib3/__init__.py", line 7, in <module> from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 29, in <module> from .connection import ( File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 41, in <module> from .util.ssl_ import ( File "/usr/lib/python3/dist-packages/urllib3/util/__init__.py", line 20, in <module> from .retry import Retry File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 20, in <module> log = logging.getLogger(__name__) AttributeError: module 'logging' has no attribute … -
Return results of Django Query as Dictionary
Suppose I have a Django model that looks like this: class User(models.Model): customer_id = models.TextField() date_time_period_start = models.DateField() date_time_period_end = models.DateField() total_sales = models.IntegerField() The underlying table looks like this: customer_id | date_time_period_start | date_time_period_end | total_sales 1 | 2023-04-01 | 2023-04-01 | 10 1 | 2023-04-02 | 2023-04-02 | 20 1 | 2023-04-03 | 2023-04-03 | 30 I would like to query using Django and return a python dictionary where the key is the value of date_time_period_start and the values is a dictionary where the keys are the columns and the values are the column values. In this example, I would like to return { '2023-04-01': {'date_time_period_start': '2023-04-01', 'date_time_period_end': '2023-04-01', 'customer_id': 1, 'total_sales': 10}, '2023-04-02': {'date_time_period_start': '2023-04-02', 'date_time_period_end': '2023-04-02', 'customer_id': 1, 'total_sales': 20}, '2023-04-03': {'date_time_period_start': '2023-04-03', 'date_time_period_end': '2023-04-03', 'customer_id': 1, 'total_sales': 30}, } I can achieve this by doing the following records = list( self.model.objects .values( "customer_id", "date_time_period_start", "date_time_period_end", "total_sales", ) ) records_dict = {} for record in records: records_dict[record["date_time_period_start"]] = { "date_time_period_start": record["date_time_period_start"], "date_time_period_end": record["date_time_period_end"], "customer_id": record["customer_id"], "total_sales": record["total_sales"], } Is there a more efficient way of doing this rather than looping through the list of records? I was trying to use values() and annotate() so something like … -
If statement in Django and Json
I have a script like this for adding the data of the table from a JSON. <script> const tableData = $('#table-data').DataTable({ dom: 'Bfrtip', "serverSide": true, "processing": true, "ajax": { "url": '{{ data_url }}' }, "columns": [ { {% comment %} "data": "pertanyaan__bidder_id__name" {% endcomment %} "data": "pertanyaan__bidder_id__name" }, {"data": "waktu_pengambilan" }, {"data": "id", "render": function(data, type, full, meta){ const statusUrl = "{{ status_url }}".replace('1', data) const actions = [] const dokumen = data actions.push(`<a href="${statusUrl}" class="btn btn-sm btn-dark" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-custom-class="tooltip-dark" title="Download" target="_blank" style="pointer-events: none;">Lihat<span class="btn-icon-end"><i class="fa fa-eye"></i></span></a>`) return actions.join('&nbsp;') } }, {"data": "keterangan"}, ] }) $('.dt-button').addClass('btn btn-primary') $('.dt-button').removeClass('dt-button') </script> the JSON gets from class PertanyaanData. This result will pass to a class called PertanyaanView class PertanyaanData(View): def get(self, request): limit = int(request.GET.get("length", 10)) offset = int(request.GET.get("start", 0)) rows = ListDokselPertanyaan.objects.all()[offset:limit].values( 'id','pertanyaan__bidder_id__name', 'waktu_pengambilan', 'pertanyaan__pertanyaan', 'keterangan', 'pertanyaan') count = rows.count() data = { 'draw': request.GET.get("draw", 1), 'recordsTotal': count, 'recordsFiltered': count, 'data': list(rows), } return JsonResponse(data) class PertanyaanView(View): def get(self, request): context = { 'title': 'Pertanyaan Dokumen Seleksi', 'data_url': reverse_lazy(conf.APP_BASE_NAME + conf.PERTANYAAN_DATA_URL_NAME), 'status_url': reverse_lazy(conf.APP_BASE_NAME + conf.PERTANYAAN_SELECT_URL_NAME, kwargs={'pk': 1}) } return render(request, 'app/pertanyaan/index.html', context) I am a beginner in Django and I don't know how to make an if statement here. For example, … -
Django database Migration Traceback (most recent call last):
i am beginner at Django python. after create the table and run the migration command i got the error was i attached below.what i tried so far i attached below. models.py from django.db import models # Create your models here. class Students(models.Model): StudentId = models.AutoField(primary_key=True) StudentName = models.CharField(max_length=500) Course = models.CharField(max_length=500) Fee =models.CharField(max_length=500) Full Error after run the migranation command : python manage.py makemigrations StudentApp Traceback (most recent call last): File "E:\django\stud_crud\manage.py", line 22, in <module> main() File "E:\django\stud_crud\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\Hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\Hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 178, in create mod = import_module(mod_path) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Hp\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1128, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'StudentApp' -
Heroku credit card
Why i can not add my credi or debit card to heroku every time it shows error please try again later My cards from egypt if any one face this problem please hellp My cards from egypt if any one face this problem please hellp. -
django channels how to send json to all users of group
i have a problem with the group_send function. If I try to run it it doesn't give me any errors but it doesn't even run. I'm using the function with django channels with redis server. It should send me the json but nothing is received from the group_send while with the self.send it arrives. Can someone help me? class Accettazioni(WebsocketConsumer): def connect(self): self.room = 'test' async_to_sync(self.channel_layer.group_add)(self.room, self.channel_name) self.accept() def receive(self, text_data=None, bytes_data=None): user = self.scope["user"] id_user = user.id id_postazione = self.scope['session']['ID'] print(user, id_user, id_postazione) text_data_json = json.loads(text_data) print(text_data_json) if 'prossimo_cliente' in text_data_json: prossima_prenotazione = richiesta_prossimo_cli() prenotazione_in_PresaInCarico(id_user, id_postazione, prossima_prenotazione) if prossima_prenotazione is not None: json_pronto = impacchetta_json(prossima_prenotazione) self.send(json.dumps({'prossima_prenotazione': json_pronto})) async_to_sync(self.channel_layer.group_send)(self.room, {'prossima_prenotazione': json_pronto}) else: self.send(json.dumps({'prossimo_cliente': 'KO'})) i tried without the async_to_sync function too but it still doesn't work. I expect the json to be sent to all users who are connected to this consumer.how can i solve? -
what is the best path to choose as a beginner (i like to go for backend)? [closed]
i have a suggestion to start with (node js) but iam thinking about python and his framework and i have another suggestion to go for php iam not sure what to start with and also iam studying html5 now so what to go next i expecting for suggestion to be a good back end -
How to correctly use djngo slippers in templates
I started using Django slippers recently and I am very confused with some things. I am trying to render a template but I keep having this error. I don't know where this error is from: {% extends 'base.html' %} {% load slippers %} {% block content %} {% #card title='video game' name='name1' %} <span>Hii</span> {% /card %} {% endblock %} This is my template. I have this error: File "C:\Users\DELL\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 241, in wrapper if any( ^^^^ RecursionError: maximum recursion depth exceeded I don't understand why I m having this issue and Django Slippers is fairly new so there is no help online. Can anyone help? -
A column naming conflict between joining tables, including an EAV and a straight table
We have an internal fork of EAV-Django and have upgraded it to Python 3, so our internal fork is similar to the new repository of django-eav2. In the application, we need to join the transaction table with 1) the eav table's email records and 2) the customer table. We use Django annotate() function to automatically generate the sample SQL code below, and please refer to the join clauses as: ... left outer join `eav_value` eav_email on ... left outer join `app_customer` on ... The problem is a naming conflict: we get a column named email from the eav_value table, and the customer table also contains a column named email. Therefore, when intending to sort by the EAV's email attribute, the clause order by email asc triggers an error saying "Column 'email' in order clause is ambiguous". Question: We could rename the EAV's email to eav_email but the change will trigger other changes on the frontend, because the frontend component relies on the column name email or customer.email. So, we wonder if there is any way to give a parent annotation to EAV attribute, e.g. in SQL query, we do instead of eav_email.value_text as email, we can do eav_email.value_text as eav.email,. … -
Forbidden error 403 with React and Django
I'm trying implement a login form where I'm passing the username and password to backend but I'm getting a 403 forbidden request error. Here is my frontend code where I'm sending username and password along with header named 'Access-Control-Allow-Origin. const login = (username, password) => { return axios .post( API_URL + "signin/", { username: "test@test.com", password: "password", }, { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", }, } ) .then((response) => { if (response.data.accessToken) { localStorage.setItem("user", JSON.stringify(response.data)); } return response. Data; }); }; This is my settings.py file in backend: ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ ...... 'rest_framework_simplejwt.token_blacklist', 'rest_framework_simplejwt', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ .......... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False CORS_ALLOW_HEADERS = ['*'] And this is the views.py file: @api_view(['POST']) def signin(request): username = request.data.get('username') password = request.data.get('password') print(username," ",password) return JsonResponse(username) I'm trying to debug this error from the past few hours but haven't found a solution yet. On trying to debug, sometimes I also get the CORS error when I make a few changes to the settings.py file. I tried searching for answers on stack overflow but those solutions didn't work for me. I know it should be a minor issue but am not … -
Errno 13: Permission denied: 'celerybeat-schedule' with Celery running on AWS ECS and SQS
I have a separate Celery Beat and Work service running in ECS. The worker appears to be connecting to SQS fine. The Beat on the other hand is giving me trouble. I used these instructions as a template for what I am doing. https://dev.to/daiquiri_team/deploying-django-application-on-aws-with-terraform-setting-up-celery-and-sqs-38ik I deviated a little bit because I already had an existing Terraform/Django project running within AWS. The Django project is also on ECS. I am having difficulty knowing what to be looking for because the error is rather vague. Why would the schedule create a Permissions denied? Is the Beat trying to write to SQS? I currently have 4 queues. I am executing the command below from the container definition: celery -A backend beat I also am running the following in my container definition because I read that ECS is always run as root. {"name": "C_FORCE_ROOT", "value": "true"} -
Deploying my nlkt chatbot to web using django
I just developed a chatbot for a client using nltk frame work, the bot works well but am having it difficult deploying it on django,tried using html form get method as my user input but it not working nor my bot response is not displaying...can someone please put me through the steps to follow.....thanks in advance I did run my code on the views on my django project if I call the url for the front page, my bot runs in my system but nothing works at the front end -
Validate data on all associated models before saving any Django models
I have two models in a Django project. One of them has a foreignkey to the other and within the admin is displayed as an inline model so that we can work with both models together. class Model1(models.Model): name = CharField(max_length=150) class Model2(models.Model): parent = ForeignKey(Model1, on_delete=CASCADE) name = CharField(max_length=15) My current goal is to be able to save Model1 in the admin and before any data is saved at all check all associated Model2 instances to make sure their 'name' field is not a certain value. This would mean that if I changed the name of Model1 and created 2 Model2 instances I would check both Model2 instances for their name incoming name value, make sure it checks out, if both do not DO NOT save ANYTHING, if they both check out, save everything. So far I have not found anything that will allow me to see the incoming values prior to saving Model1. Instead, I can only check each incoming Model2 right before it is saved.