Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serving a Dash dashboard from Django hosted app to an external webpage
I am currently hosting my dashboard on a url like the following: https://xxx.herokuapp.com/dashboard/ExternalDashboard using Django and serving an HTML page with the following contents: <!DOCTYPE html> <html> <head> <title>External Dashboard</title> <style> body, html { height: 100%; margin: 0; padding: 0; } #plotly-app-container { height: 100%; } </style> </head> <body> <div id="plotly-app-container"> {% load plotly_dash %} {% plotly_app name="ExternalDashboard" ratio=1 %} </div> </body> </html> This works very well and my dash dashboard is interactable and everything is good. Now I want to serve this Dashboard on another website say https://YYY.herokuapp.com/FetchDashBoard, here I also want to send back some information such as an authentication token which i will use on my dashboard to check which plots to display. From the official dash documentation (https://dash.plotly.com/integrating-dash) on integrating dash I gather zero useful information. Im not a frontend developer and simply creating an html page on https://YYY.herokuapp.com/FetchDashBoard with the following contents just yields a blank page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Display Dashboard</title> </head> <body> <div id="dash-app"></div> <script> var setter = window.dash_embedded_component.renderDash( { url_base_pathname: "https://xxx.herokuapp.com/dashboard/ExternalDashboard"}, 'dash-app', sharedData ); </script> </body> </html> Bear in mind that im not sending any data to begin with, I just want to see … -
how to create user profile and save user data from data base?
I want to create a user profile, I will add that user to my own template, when a user registers, it will be registered. His profile name, username, email address will be added. As soon as he adds the post, all the posts will be added to his profile history. How to make this thing in django? I want to create a user profile, I will add that user to my own template, when a user registers, it will be registered. His profile name, username, email address will be added. As soon as he adds the post, all the posts will be added to his profile history. How to make this thing with django? -
How to allow null value on serializer when the field in the model is required?
Given the following payload, models.py, and serializers.py in Django (DRF): payload { "created_by": 6, "brand": 1, "foo_details": [ { "quantity": 123, "price_estimation": 456 }, { "quantity": 789, "price_estimation": 1011 } ] } models.py class Foo(models.Model): created_by = models.ForeignKey(CustomUser, on_delete=models.PROTECT) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) # OTHER FIELDS HERE class FooChild(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name="foo_details") quantity = models.PositiveIntegerField(default=0) price_estimation = models.PositiveIntegerField(default=0) # OTHER FIELDS HERE serializers.py class FooChildSerializer(serializers.ModelSerializer): # foo = serializers.PrimaryKeyRelatedField(read_only=True, required=False) -> LINE 2 class Meta: model = FooChild fields = ["id", "foo", "quantity", "price_estimation", ...] class FooSerializer(serializers.ModelSerializer): # foo_details = FooChildSerializer(many=True) -> LINE 9 # foo_details = serializers.DictField(child=serializers.CharField(), many=True) -> LINE 10 class Meta: model = Foo fields = ["id", "created_by", "brand", "foo_details", ...] def create(self, validated_data): # I want to save the payload to `Foo` and `FooChild` inside this function at the same time, below is my unsuccessful attempt # print(validated_data) # validated_data.pop("foo_details") # foo = Foo.objects.create(**validated_data) -> LINE 21 # foo_child = FooChild.objects.create(foo=foo) # return foo The problem I'm having right now is, when I tried to POST the payload, DRF complained that foo field in FooChild is required, which is understandable, the problem is, the id of the Foo exists only after I created … -
what is the different between migrate and makemigrations?
What is the difference between the migrate and makemigrations ? I want to know different between both and why we have to both in django. after changing model.py file and that affect database then we have to run this two command py manage.py makemigrations user py manage.py migrate -
How to combine queries in django that span foreign key relationships?
Suppose I have two models: class Team(models.Model): name = models.CharField() class Player(models.Model): name = models.CharField() team = models.ForeignKey(Team) Now, I want to filter Player objects through their name as well as the name of their team. So for example if user input is aa, I want all Players who have aa in their name OR in their team's name. So far I have tried to use two queries like this: players = Player.objects.filter( name__icontains=request.GET.get("q", ""), # ...other filters ) more = Player.objects.filter( team__name__icontains=request.GET.get("q", ""), # ...other filters ) players = players.union(more) This gives the results, but it has its own problems: i) It gives duplicate results in cases where the search query matches both, the player name and the team name (.union method does not support .distinct) ii) It searches the database twice which can be an expensive operation. So I would like it to run in just one query. iii) It is not DRY. You have to repeat the other filters twice. So is there a way to get the results accurately? -
Django multi tenant help required
I am currently building saas app using django_multitenant package and i read and followed all the detail given in the docs and while using Django admin panel everything is fine. If we create any object from panel the object automatically get tenant assigned to it but while using an API and It kept asking the tenant id how to solve it. # setting MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "apps.api_auth.middlewares.MultitenantMiddleware", # 'django_multitenant.middlewares.MultitenantMiddleware', ] # custom middleware class MultitenantMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): jwt_auth = JWTAuthentication() # Authenticate the user auth_result = jwt_auth.authenticate(request) if auth_result is not None: user, _ = auth_result if user and not user.is_anonymous: tenant = Institute.objects.filter(user=user).first() set_current_tenant(tenant) response = self.get_response(request) unset_current_tenant() return response # models class Institute(TenantModel): name = models.CharField(max_length=100) class TenantMeta: tenant_field_name = "id" class CustomUserManager(TenantManagerMixin, UserManager): pass class User(TenantModel, AbstractUser): institute = TenantForeignKey( "tenant.institute", on_delete=models.CASCADE, blank=True, null=True ) objects = CustomUserManager() class TenantMeta: tenant_field_name = "institute_id" class SessionYear(TenantModel): start_year = models.DateField() end_year = models.DateField() is_deleted = models.BooleanField(default=False) is_active = models.BooleanField(default=False) institute = TenantForeignKey("tenant.institute", on_delete=models.CASCADE) class TenantMeta: tenant_field_name = "institute_id" # API view from django_multitenant import views from rest_framework import viewsets, permissions from apps.tenant import tenant_func … -
nginx + uwsgi upstream prematurely closed connection while reading response header from upstream
I'm using uwsgi and nginx to deploy a Django project which using VUE3 and Django. And nginx is in a docker container.I have tried several conf combinations, only the follow one works. location /cseq/ { root /usr/share/nginx/html; #try_files $uri $uri/ /cseq/index.html; index index.html index.htm; } location /cseq/api/ { proxy_pass http://xxx:8001; 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; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; uwsgi_buffer_size 16k; uwsgi_busy_buffers_size 24k; } [uwsgi] http=:8001 chdir=/root/project/cseq/cseq-backend module=cseq.wsgi:application master=true vacuum=true max-requests=5000 workers= 4 threads = 2 buffer-size = 65536 daemonize=/root/project/cseq/cseq-backend/uwsgi.log My question is: in uwsgi conf, using http works, but change http to socket, nginx has a error:upstream prematurely closed connection while reading response header from upstream. when I change both conf to the follow location /cseq/ { root /usr/share/nginx/html; #try_files $uri $uri/ /cseq/index.html; index index.html index.htm; } location /cseq/api/ { include uwsgi_params; uwsgi_pass 127.0.0.1:8001; } [uwsgi] socket=:8001 chdir=/root/project/cseq/cseq-backend module=cseq.wsgi:application master=true vacuum=true max-requests=5000 workers= 4 threads = 2 buffer-size = 65536 daemonize=/root/project/cseq/cseq-backend/uwsgi.log the error becomes failed (111: Connection refused) while connecting to upstream, in both errors, uwsgi didn't has any connection. Any ideas or solutions? I want to use nginx and uwsgi to deploy a Django project -
Case insensative search/filter in django
at my Search class of django project I try to get products query from db but it case sensative not matter what i tried, i still can not enhance my search query maybe not that way to solution, i will find a possible way to get it right but one and biggest broblet that i use Sqlite3 wher is method (name__icontains=search_query) not valid, i mean valid but does not work part of Search class: def get_queryset(self): search_query = self.request.GET.get('q') print(f"start q {search_query}") print(Product.objects.filter(name__icontains=search_query)) print(repr(search_query),"----------") if search_query: # Filter products where label contains the search query (case-insensitive) return Product.objects.filter(name__icontains=search_query) else: return Product.objects.none() -
Why is Django prefetch_related resulting in 100s of extra SQL queries?
My relationships are as follows: A Portfolio has a many 2 many relationship to LoanTape through PortfolioLoanTapes A Quote has many LoanTapes A Quote has many Documents I am trying to query a Portfolio and all its related starred documents in a GET portfolio API call in DRF ModelViewSet. models.py class Portfolio(models.Model): loan_tapes = models.ManyToManyField("LoanTape", through="PortfolioLoanTapes") class PortfolioLoanTapes(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.PROTECT) loan_tape = models.ForeignKey(LoanTape, on_delete=models.PROTECT) class LoanTape(models.Model): portfolios = models.ManyToManyField("Portfolio", through="PortfolioLoanTapes") quote = models.ForeignKey("Quote", on_delete=models.PROTECT, blank=False, null=False, related_name="loan_tapes") class Quote(models.Model): ... class Document(models.Model): quote = models.ForeignKey(Quote, on_delete=models.PROTECT, related_name="documents") is_starred = models.BooleanField(default=False) view.py def get_queryset(self): starred_documents_qs = Document.objects.filter(is_starred=True) quotes_prefetch = Prefetch('quote__documents', queryset=starred_documents_qs, to_attr='starred_documents') loan_tapes_prefetch = Prefetch('portfolioloantapes_set__loan_tape', queryset=LoanTape.objects.prefetch_related(quotes_prefetch)) qs = Portfolio.objects.prefetch_related(loan_tapes_prefetch).filter(deleted__isnull=True) return qs serializer.py class PortfolioDetailSerializer(serializers.ModelSerializer): loan_tapes = PortfolioLoanTapeSerializer(many=True, read_only=True, source="portfolioloantapes_set") class PortfolioLoanTapeSerializer(serializers.ModelSerializer): def to_representation(self, instance): ret = super().to_representation(instance) ret.update(LoanTapeSerializer(instance.loan_tape).data) return ret class LoanTapeSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField() def get_image_url(self, instance): if starred_docs := getattr(instance.quote, 'starred_documents', []): return starred_docs[0].url test.py (missing some setup objects) def test_retrieve_query_count(self): with self.assertNumQueries(4): response = self.client.get(f"/api/v1/portfolios/{portfolio.id}/", **self.headers) self.assertEqual(response.status_code, 200) When asserting the number of queries in the test above, Django is making 224 DB calls!! Are my prefetch objects not setup correctly? Is there a more efficient path in the prefetch? I'm quite lost and can't seem … -
Django crispy form how to format while typing
super_amount = models.DecimalField( max_digits=20, decimal_places=2, default=Decimal(0), ) {{ form.super_amount|as_crispy_field }} I have this field in my form but I want this field to be formatted with commas while typing in browser. So if I write 123456789, it will be shown like this everytime I write a number: 1 -> 12 -> 123 -> 1,234 -> 12,345 -> ... -> 123,456,789 https://stackoverflow.com/a/39279790/14253522 I tried to use this but after 6 digit, field clears itself. I tried to work around this problem but wasn't able to solve it. -
NGINX and Django not in debug serving some static files and some no
I am experiencing some weird behaviour after switching off DEBUG on Django, behind NGINX reverse proxy. I am testing it on a Armbian Linux with Python 3.7.3. Django project has the manage.py inside the folder folder configuration is - /var/webserver/backend - manage.py - backend - settings.py - static - img (contains collected plus my logo and favicon) - admin (the collected admin files) The NGINX configuration is as following (the static part, the rest is a reverse proxy with a self signed certificate): location /static { autoindex on; autoindex_exact_size off; alias /var/webserver/backend/static; } The settings.py static part is as following, staticfiles app is in the APPS: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' I run the manage.py command while in the /var/webserver/backend directory, nginx is ran as service. I think I have tried all combinations of "slashes" both inside the NGINX configuration and settings.py (before, after, both, none) This configuration is the nearest to work, the situation is the following: The logo.png and favicon.ico inside the static/img folder are displayed correctly all the css, js or others are not loaded (page is completely without style) There are no 404 in the logs (either Django or NGINX access.log shows 200). … -
Django apps have circular dependency, causes foreign key models not to migrate
I have two django apps that have foreign keys to each other An api app and another app called blog Here is my models.py for the blog app class Post(models.Model): uuid = models.UUIDField(default=uuid.uuid4, primary_key=False, unique=True) title = models.CharField(max_length=600) authors = models.ManyToManyField('Author', related_name='authors') tags = models.ManyToManyField('Tag', related_name='tags') date_published = models.DateField(auto_now_add=True) # store table of contents as JSON table_of_contents = models.TextField(default=dict) # s3 link to thumbnail thumbnail = models.URLField(max_length=300) # each post belongs to a blog blog = models.ForeignKey('api.Blog', on_delete=models.CASCADE, default=0) slug = models.SlugField(max_length=100, default='') # store markdown as text content = models.TextField(default='') # link to post url = models.URLField(default='') # for json serialization def as_dict(self): return { "title": self.title, "slug": self.slug, "authors": [ author.as_dict() for author in self.authors.all() ], "tags": [ tag.as_dict() for tag in self.tags.all() ], "date_published": "01/01/2001", "table_of_contents": self.table_of_contents, "thumbnail": self.thumbnail, "id": str(self.uuid), } def __str___(self): return self.title class Author(models.Model): name = models.CharField(max_length=100) blog = models.ForeignKey('api.Blog', on_delete=models.CASCADE, default=0) def as_dict(self): return { "name": self.name, "profile": self.name } def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=50) blog = models.ForeignKey('api.Blog', on_delete=models.CASCADE, default=0) def as_dict(self): return { "name": self.name } def __str__(self): return self.name And my models.py for my "api" app class Blog(models.Model): # Foreign key to the associated tenant in … -
Django objects.get not working when using the request data
I couldn't understand why this code isn't working: I'm currently using Django as cms, and nextjs as fronted: while I was testing the get request i had a lot of trouble to make the Member.objects.get(firstname='Alessia') working and also filter doesn't work at all. from django.http import HttpResponse from django.http import JsonResponse from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.decorators import api_view from simulazione.models import * from simulazione.api.serializers import * @api_view(['GET']) def get_data(request): nome = request.GET.get('name', None) try: dear = Member.objects.get(firstname=nome) serializer = MemberSerializer(dear) data = {'hello': 'hello2'} return JsonResponse(serializer.data) except: print("Server error") Everytime I run this, i get this error: AssertionError at /simulazione/api/get_data/ Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> -
Django view caching: how to set expire at time?
I would like to cache some view until end of month. e.g. @cache_page_expire_at_end_of_month def some_view(request): ... I found this old question Django per-view caching: set expiry time rather than cache timeout? But I can't get it to work. -
Difficulty Establishing Secure Connection Between Web Server and MQTT Server
I'm currently working on a project for monitoring robots, and I've developed a web platform using Django and Vue for data acquisition and visualization. At present, I'm utilizing an MQTT server to transmit all my data. However, I've encountered an issue while trying to configure communication between my web page, which has an SSL certificate generated by Certbot, and the MQTT server implemented on a Raspberry Pi 4. I've attempted to generate an SSL certificate for MQTT using OpenSSL, but I've been unsuccessful in establishing a connection between the web server and the MQTT server. It seems that the web page doesn't allow unencrypted connections with the MQTT server. I'm employing the WebSocket protocol for this connection. Additionally, I'm unable to use Certbot to generate an SSL certificate for the Raspberry Pi, as I don't have my own domain for the Raspberry Pi's IP address. Does anyone have any ideas about what might be happening or any alternative methods for securely establishing this connection? Thanks in advance for your assistance. When attempting to establish the connection between my web server and the MQTT server, I used an SSL certificate generated by Certbot on the web server and tried to generate … -
What's an easy and safe way to provide users access to MySQL database so they can interact with it (CRUD)?
I'm creating a database for a small community and would like to set up a web interface for them to interact with it. I'd like users to be able to use a password to access their own records for changes. Also I assume there's a way to assign users to groups to be able to access a wider set of rows. Someone mentioned Django and I see that there are other possibilities like PHP. I have database experience, but little experience with web pages. I don't have much javascript or CSS. I haven't tried anything yet. I'm still considering how to start. -
Postgres15 Grant All on schema public not workiing
My code used to work fine with postgres 12, now with postgres 15 my django project can't run migrations. I found many answers suggesting to GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO <user>, but it does not work for me as shown: Below the user named django needs to be able to create tables in the public schema, so it can run migrations: sudo -u postgres psql could not change directory to "/home/john/project/src": Permission denied psql (15.6 (Debian 15.6-0+deb12u1)) Type "help" for help. postgres=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO django; GRANT postgres=# \q (project) john@vps-demo:~/project/src$ psql -U django my_db Password for user django: psql (15.6 (Debian 15.6-0+deb12u1)) Type "help" for help. my_db=> CREATE TABLE test_table1 (id INT); ERROR: permission denied for schema public LINE 1: CREATE TABLE test_table1 (id INT); ^ my_db=> -
function on Django to check user in database
I want to write a function to check a user in the database, can anyone help? can someone help i am learning Django I try many ways but ... ------------view.py---------------- def user_enter(request): print("hello") if request.method == "POST": enter_user_email=request.POST.get('enter_user_email') enter_user_pass=request.POST.get('enter_user_pass') print(enter_user_pass) print(enter_user_email) data=User.objects.filter(email_name = enter_user_email,user_password = enter_user_pass).exists() return render(request, 'main.html',{'data':data}) --------------HTML--------------- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="static/css/style.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> </head> <body> <div class="container mx-auto mt-2" style="width: 500px;" id="input_name_pass"> <img src="static/user.png" alt="..." id='user_image' class="img-thumbnail mx-auto" style="width: 200px;"> <form action="" method = "POST"> {% csrf_token %} <div class="input-group input-group-sm mb-3 mt-4"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroup-sizing-sm">User</span> </div> <input type="text" class="form-control" aria-label="Small" aria-describedby="inputGroup-sizing-sm" name = "enter_user_email"> </div> <div class="input-group input-group-sm mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroup-sizing-sl">Pass</span> </div> <input type="password" class="form-control" aria-label="Small" aria-describedby="inputGroup-sizing-sm" name = "enter_user_pass"> </div> <button type="submit" class="btn btn-primary mt-3" onclick="location.href='{% url 'user_enter' %}'">Enter</button> </form> <button type="button" class="btn btn-primary mt-3" onclick="location.href='{% url 'user_registration' %}'">Create User</button> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> -
zero tasks are running in Celery with supervisor
I am using Celery with Django, and it works perfectly fine when I use the celery command and run the worker and beat individually, but when I use supervisor to run Celery as a daemon, no tasks start running. supervisorctl status all [sudo] password for ahmed: beat RUNNING pid 22064, uptime 1:29:20 worker RUNNING pid 22063, uptime 1:29:20 celery.conf file in /etc/supervisor/conf.d/celery.conf ; ========================================== ; celery worker config ; ========================================== [program: worker] command=/home/ahmed/.local/bin/celery -A decimal_trade worker -l info directory=/home/ahmed/PycharmProjects/decimal-trade user=ahmed numprocs=1 stdout_logfile=/home/ahmed/PycharmProjects/decimal-trade/celery/log/worker.log stderr_logfile=/home/ahmed/PycharmProjects/decimal-trade/celery/log/worker.err.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 ; priority 998 executes first and then 999 ; ======================================== ; celery beat config ; ======================================== [program: beat] command=/home/ahmed/.local/bin/celery -A decimal_trade beat -l info directory=/home/ahmed/PycharmProjects/decimal-trade user=ahmed numprocs=1 stdout_logfile=/home/ahmed/PycharmProjects/decimal-trade/celery/log/beat.log stderr_logfile=/home/ahmed/PycharmProjects/decimal-trade/celery/log/beat.err.log autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=999 The worker log -------------- celery@ahmed-Lenovo-V14-G1-IML v5.3.6 (emerald-rush) --- ***** ----- -- ******* ---- Linux-6.2.0-39-generic-x86_64-with-glibc2.35 2024-03-14 18:19:37 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: decimal_trade:0x7fa64756c3d0 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: redis://localhost:6379/0 - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] … -
@api_view method not works but post method works django rest api
I have imported django_restframework.decorators from api_view @api_view(['POST']) def post_cart(self,request): serializer = CartItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) curl -X POST -H "Content-Type: application/json" http://127.0.0.1:8000/api/cart-items/ -d "{\"product_name\":\"name\",\"product_price\":\"41\",\"product_quantity\":\"1\"}" When I use @api_view(['GET']) I get this error { "detail": "Method \"POST\" not allowed." } But When I change like this it works def post(self,request): serializer = CartItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) curl -X POST -H "Content-Type: application/json" http://127.0.0.1:8000/api/cart-items/ -d "{\"product_name\":\"name\",\"product_price\":\"41\",\"product_quantity\":\"1\"}" It returns success 200 { "status": "success", "data": { "id": 5, "product_name": "item", "product_price": 12.5, "product_quantity": 5 } } -
Django REST Framework login and logout views
I'm building a system using django, django rest framework, django oauth toolkit, django axes in a microservices architecture but I have some doubts. Currently I have my "login" view on the client that takes the username and password from the POST request and sends it to my "UserLoginAPI" API, in the "UserLoginApi" view I validate the user and password in the "UserLoginSerializer" serializer, I check if the user is not blocked in django axes and I create a token for this user with oauth, the serializer returns the authenticated user and the token and "UserLoginApi" updates the last_login with update_last_login, I saw in a discussion on stackoverflow that it should be used update_last_login instead of login(request, user), then I return the token back to the "login" view on the client, and on the client I take this token and store it in the session and with middleware I check in each request if the token exists and if the token exists, if it has already expired, if it exists and has not expired, I update the session user with the user associated with the token. And at logout I do the same thing but I use logout(request) to log out … -
how to install mysqlclient in windows?
I am a windows 10 user, for my django project when i try to download mysqlclient module it displays error , i tried various strategies, please help me. C:\Users\sachin>pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Using legacy setup.py install for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\sachin\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\sachin\AppData\Local\Temp\pip-install-ye9s3zyg\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\sachin\AppData\Local\Temp\pip-install-ye9s3zyg\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\sachin\AppData\Local\Temp\pip-record-yz3e0ytd\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\sachin\appdata\local\programs\python\python37-32\Include\mysqlclient' cwd: C:\Users\sachin\AppData\Local\Temp\pip-install-ye9s3zyg\mysqlclient Complete output (29 lines): running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb_init_.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb.mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.38.33130\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(2,1,1,'final',0) -D__version_=2.1.1 "-IC:\Program Files (x86)\MariaDB\MariaDB Connector C\include\mariadb" "-IC:\Program Files (x86)\MariaDB\MariaDB Connector C\include" … -
Null value set to True, but still it violates not-null constraint
I am trying to set a null sidebar from the Django admin interface as shown below: However, when I press "Save" I get an IntegrityError error: IntegrityError at /admin/qa/howquestion/112/change/ null value in column "sidebar_id" violates not-null constraint DETAIL: Failing row contains (112, <p>prettyprint a JSON file<br></p>, To pretty print a JSON file in Python, you can use the json m...). It's strange because null is set to True: sidebar = models.ForeignKey(Sidebar, on_delete=models.SET_NULL, related_name='qa_sidebars',null=True, blank=True) And I have applied migrations too. Please note that the error does not happen in development where an SQLite3 database is used. This only happens in deployment where I am using a PostGreSQL database. I have ran out of options. I searched everything and still don't understand this. Anyone can help? -
How do I save the pasword as hashed password in postgressql database
I have created a custom user model Employee in Django that extends AbstractBaseUser. The Employee model has a password field of type CharField. I am using PostgreSQL as the database. When creating a new Employee instance using the EmployeeManager.create_employee method and providing a plaintext password, the password is not being saved as a hashed value in the PostgreSQL database. Instead, it is being stored as plaintext. Here's the relevant code: model.py from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.hashers import make_password, check_password class OrganizationManager(BaseUserManager): def create_organization(self, email, name, **extra_fields): if not email: raise ValueError(_('The Email field must be set')) email = self.normalize_email(email) organization = self.model(email=email, name=name, **extra_fields) return organization class Organization(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) name = models.CharField(_('name'), max_length=150) is_active = models.BooleanField(_('active'), default=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) groups = models.ManyToManyField( 'auth.Group', related_name='org_groups', # Custom related name for Organization blank=True, help_text=_( 'The groups this organization belongs to. A user will gain all permissions granted to each group.'), ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='org_user_permissions', # Custom related name for Organization blank=True, help_text=_('Specific permissions for this organization.'), ) password = None # Override the password field … -
Django + React Development Setup for a Hybrid App
I'm using Django + React hybrid setup. Django does not simply act as a backend to API but actually renders pages. The setup works in production with some urls routed to Django's templating system and others (starting with 'app/') rendered from index.html + static files from React build. This works in production. However, I'm trying to get Django development server (localhost:8000) work with react development server (localhost:3000) as follows. Django backend Urls.py urlpatterns = [ # React urls re_path(r'^app/.*',views.application,name='application'), # Django urls path("", include("my_app.urls")), ] Views.py def application(request, upstream='http://127.0.0.1:3000'): upstream_url = upstream + request.path with urllib.request.urlopen(upstream_url) as response: content_type = response.headers.get('Content-Type') # print('CONTENT TYPE: ',content_type) if content_type == 'text/html; charset=UTF-8': response_text = response.read().decode() content = engines['django'].from_string(response_text).render() else: content = response.read() return HttpResponse( content, content_type=content_type, status=response.status, reason=response.reason, ) React frontend App.js function App() { const HomePage = () => { return (<h1>Home Page</h1>); } const TestPage= () => { return (<h1>Test Page</h1>); }; return ( <BrowserRouter> <Routes> <Route path="app/" element = {<HomePage/>}/> <Route path="app/test" element = {<TestPage/>}/> </Routes> </BrowserRouter> ); }; .env PUBLIC_URL = app Both /app and app/test urls are accessible on port 3000. However, on port 8000 where Django development server is running I can only get /app while …