Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Updating Cart Total Amount Dynamically After Adding Items with AJAX in Django is not working properly
I created a cart item total section for my website <div class="col-md-4"> <div class="cart-item total-section"> <h3>Subtotal: <span class="total">$50.00</span></h3> <h3>Discount: <span class="total">$50.00</span></h3> <h3>Shipping: <span class="total">Free</span></h3> <h3>Total: <span class="total">{{cart_total_ammount}}</span></h3> <button class="btn btn-checkout">Proceed to Checkout</button> </div> </div> In the above code I am taking total ammount of the cart In " <h3>Total: <span class="total">{{cart_total_ammount}}</span></h3> " this line for this I created a javascript file So, In function.js: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let product_image = $(".product-image").val() let product_pid=$(".product-pid").val() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("PId:", product_pid); console.log("Image:", product_image); console.log("Title:", product_title); console.log("Price:", product_price); console.log("Image URL:", product_image); console.log("Current Element:", this_val); $.ajax({ url: '/add-to-cart', data: { 'id': product_id, 'pid': product_pid, 'image':product_image, 'qty': quantity, 'title': product_title, 'price': product_price }, dataType: 'json', beforeSend: function(){ console.log("Adding products to cart"); }, success: function(res){ this_val.html("Go to Cart") console.log("Added products to cart"); $(".cart-items-count").text(res.totalcartitems) $(".total").text(res.cart_total_ammount) //#p } }) }) In the above javascript file you can see that I created the cart_total_ammount section. But it is not working I mean that instade of taking cart_total_ammount it is taking totalcartitems and In my views.py: def cart_view(request): cart_total_ammount=0 if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_ammount+= int(item['qty']) item['image'] = request.session['cart_data_obj'][p_id]['image'] # add this line return render(request, "core/cart.html",{"data":request.session['cart_data_obj'],'totalcartitems': … -
Blacklisting Network Range on django-blacklist
I've noticed recently that my django-website is being crawled by a number of spammy bots, so while looking for a way to block this IP-range I came across django-blacklist. It works well for the most part, and I've successfully blocked single IPs, but when I tried to block a range (51.222.253.0 - 51.222.253.255), it seems to be unsuccessful. My inputs were: Address = 51.222.253.0 & Prefixlen = 24 (see image below). I've read the docs, and can't seem to get more clarity on this topic, however, this isn't a strong suit of mine so let me know if I've done something wrong. All help is appreciated! -
Django application experiencing "CSRF token missing" error specifically for POST requests when deployed with Nginx and Gunicorn
I've deployed a Django application using Nginx and Gunicorn, and I'm encountering a "CSRF token missing" error specifically for POST requests. Here's a brief overview of my setup: I've deployed my Django application on an Ubuntu server using nginx and gunicorn. My Django app worked perfectly when using it locally, but now on the server I only get this error when doing POST requests: { "detail": "CSRF Failed: CSRF token missing." } [This is the tutorial we followed to set everything up on our server] (https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu) For authentication we use django_auth_adfs (microsoft). These are my setup files: nginx/sites-available/<our_project>: server { server_name <our_domain.com>; ignore_invalid_headers off; underscores_in_headers on; location / { root <location/to/frontend>; } location /oauth2/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /login_redirect { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location ~ \.well-known { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /api/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /admin/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/sel2-4.ugent.be/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/sel2-4.ugent.be/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 = <our_domain.com>) { return 301 https://$host$request_uri; } # managed by Certbot … -
I got a "Field 'id' expected a number but got 'h'." error while submitting a form with a video url(many to one) in Django
I am new coding in Python and using Django, and I am having troubles in my project when submiting the form including a video url I get this error : "ValueError at /edit_account_details/5/ Field 'id' expected a number but got 'h'. Request Method: POST Request URL: http://127.0.0.1:8000/edit_account_details/5/ Django Version: 4.2.10 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'h'. Exception Location: C:.\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields_init_.py, line 2055, in get_prep_value Raised during: core.views.edit_profile Python Executable: C:.\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.13 Python Path: ['C:\...\Dessoc\dessoc', 'C:\.\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\.\AppData\Local\Programs\Python\Python39\DLLs', 'C:\.\AppData\Local\Programs\Python\Python39\lib', 'C:\.\AppData\Local\Programs\Python\Python39', 'C:\.\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Wed, 13 Mar 2024 21:28:03 +0000" if I leave the url field empty it work perfect, My code for model is: class Account(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_of_deceased = models.DateField() rest_location_coordinates = models.CharField(max_length=255) rest_location_info = models.TextField(blank=True) biography = models.TextField(blank=True) photo_gallery = models.ManyToManyField('Photo') video_gallery = models.ManyToManyField('Video') guestbook_entries = models.ManyToManyField(GuestbookEntry, blank=True, related_name='account_guestbook_entries') def __str__(self): return f"{self.first_name} {self.last_name} - {self.profile.user.username}" class Photo(models.Model): account_id = models.ForeignKey(Account, on_delete=models.CASCADE) title = models.CharField(max_length=255) image = models.ImageField(upload_to='photos/') def __str__(self): return self.title class Video(models.Model): account_id = models.ForeignKey(Account, on_delete=models.CASCADE) title = models.CharField(max_length=255) video_url = models.URLField() def __str__(self): return self.title def save_form_data(self, instance, data): if data is None: return # Check if 'video_url' is present in … -
Template is not working correctly in Django
I am trying to create a page for logistic company where a user can request a quote through this page. I am trying to implement a page where I can click on an add product button and then it will allow me to choose the product from the dropdown menu and then let me specify a quantity for it. this is my models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.utils import timezone from .states import STATE_CHOICES,prod_choices class Product(models.Model): name = models.CharField(max_length=100,choices=prod_choices, unique=True) def __str__(self): return self.name class Quote(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=60) email = models.EmailField() address=models.CharField(max_length=150) ph_num= PhoneNumberField() state=models.CharField(max_length=45,choices=STATE_CHOICES,default="State") city=models.CharField(max_length=20,default="City") pincode = models.CharField(max_length=10) created_at = models.DateTimeField(auto_now_add=True) order_id=models.CharField(max_length=255, unique=True,default="#") process_status=models.BooleanField(default="False") def generate_order_id(self): state_abbreviation = self.state[:3].upper() city_abbreviation = self.city[:3].upper() current_datetime = timezone.now().strftime('%Y%m%d%H%M%S') order_id = f"{state_abbreviation}_{city_abbreviation}_{self.name}_{current_datetime}" return order_id def __str__(self): return f"Quote {self.id}" class QuoteProduct(models.Model): quote = models.ForeignKey(Quote, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField(default=0) def __str__(self): return f"{self.product.name} - {self.quantity}" This is my forms.py from django import forms from .models import Quote from .models import QuoteProduct class QuoteForm(forms.ModelForm): class Meta: model = Quote fields = ['name', 'email', 'address', 'ph_num', 'state', 'city', 'pincode'] class QuoteProductForm(forms.ModelForm): class Meta: model = QuoteProduct fields = ['product', 'quantity'] This is my … -
Django Adding Square Brackets In Admin-Related Views
I am hosting two Django applications on a webserver and I recently upgraded all my packages to more recent versions, along with bringing the project to Python 3.12, which was generally beneficial. In doing so, I noticed that square brackets ("[]") started appearing in seemingly random views associated with admin views. To be specific, when looking at individual models in the admin view AND on the sign-in page, which I believe Django admin heavily handles. It's not mission critical to solve, and there's nothing in the source code that I know of that would cause this, and no code changes were made apart from upgrading versions. I would think it's some random setting I have to turn off but I've spent a good amount of time trying to figure it out. Admin Model View Example 1 Admin Model View Example 2 Admin Login Standard Login I've tried going in a bringing the version down on a couple of packages, but there a multitude of packages in the dependencies and for the sake of where I'd like to take the project, I'd want it to use updated versions of packages as there are certain features I can't utilize properly unless both … -
how can i solve postman error in django web app?
i have a django web app. when i try to post a request in post man i get some errors. what is the solution?[enter image description here](https://i.stenter image description hereack.imgur.com/mWggv.png)[[enter image description here](https://i.stack.imgur.com/zxIS0.png)](https://i.stack.imgur.com/55VfT.png) i tried many times for solving this problem but everytime i got 500 internal errors in postman. -
I am new to Python. Please help me if there Is any way to solve this error
`` `PS C:\Users\hp\OneDrive\Desktop\Car\car> python manage.py makemigrations No changes detected Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\utils.py", line 230, in close_all connection.close() File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable` `` I am developing a project on a car showroom management system.I just opened the vs code this error appeared and my django administration is also not working properly.This image is of django administration This is django administration's Login Page. -
How to configure Apache to deploy a project with Django and React?
After testing on localhost and checking that the application works, I want to deploy it from Apache (xampp). I am using Windows Server 2016 operating system, Python 3.11.8. I have also downloaded the file mod_wsgi-4.9.2-cp311-cp311-win_amd64.whl I have tried to modify the Apache configuration (httpd.conf), adding a virtualhost (80) for the frontend and it worked correctly. The problem occurs when I want to add another virtual host (8000) for Django, causing Apache to fail to start: <VirtualHost *:80> ServerName fichaje.local DocumentRoot "C:/Users/Administrador/Documents/fichaje/frontend/build" <Directory "C:/Users/Administrador/Documents/fichaje/frontend/build"> Options Indexes FollowSymLinks AllowOverride All Require all granted LoadFile "C:/Users/Administrador/AppData/Local/Programs/Python/Python311/python311.dll" WSGIPythonHome "C:/Users/Administrador/AppData/Local/Programs/Python/Python311" LoadModule wsgi_module "C:/Users/Administrador/AppData/Local/Programs/Python/Python311/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp311-win_amd64.pyd" <VirtualHost *:8000> ServerName fichaje_back.local Alias /static "C:/Users/Administrador/Documents/fichaje/static" <Directory "C:/Users/Administrador/Documents/fichaje/static"> Require all granted <Directory "C:/Users/Administrador/Documents/fichaje/fichaje"> <Files wsgi.py> Require all granted </Files> </Directory> # Script WSGI WSGIDaemonProcess fichaje python-path=C:/Users/Administrador/Documents/fichaje;C:/Users/Administrador/Documents/fichaje/myenv/Lib/site-packages <IfModule mod_wsgi.c> WSGIPythonHome "C:/Users/Administrador/AppData/Local/Programs/Python/Python311" </IfModule> -
Djoser, does not send email, I do not know what else to do
I am making a base project to send emails with djoser, but I am not receiving any confirmation email -I have two-step verification enabled on your main Gmail account. -I have generated a password for the application. This is my configuration settings. setting.py # Simple_JWT settings SIMPLE_JWT = { "AUTH_HEADER_TYPES": ("JWT",), "ACCESS_TOKEN_LIFETIME": timedelta(minutes=60), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": True, "UPDATE_LAST_LOGIN": True, } # Email settings EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_HOST_USER = os.environ.get("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD") EMAIL_USE_TLS = True # Djoser settings Djoser = { "LOGIN_FIELD": "email", "USER_CREATE_PASSWORD_RETYPE": True, "ACTIVATION_URL": "/activate/{uid}/{token}", "SEND_ACTIVATION_EMAIL": True, "SEND_CONFIRMATION_EMAIL": True, "PASSWORD_CHANGED_EMAIL_CONFIRMATION": True, "PASSWORD_RESET_CONFIRM_URL": "/password-reset/{uid}/{token}", "SET_PASSWORD_RETYPE": True, "PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND": True, "TOKEN_MODEL": None, "SERIALIZERS": { "user_create": "accounts.serializers.UserCreateSerializer", "user": "accounts.serializers.UserCreateSerializer", "user_delete": "djoser.serializers.UserDeleteSerializer", }, "EMAIL": { "activation": "accounts.email.ActivationEmail", "confirmation": "accounts.email.ConfirmationEmail", "password_reset": "accounts.email.PasswordResetEmail", "password_changed_confirmation": "accounts.email.PasswordChangedConfirmationEmail", }, } When I register it accepts my request but does not send anything 14/Mar/2024 09:38:53] "POST /api/auth/users/ HTTP/1.1" 201 103 How could I solve this proble -
Requested setting DEBUG, but settings are not configured
when im in terminal start my django project show that eror django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. im set my dada base as postgresql to sqlite and chek my setting file -
Navigating to a link that is not part of the Django application is throwing a 404 error
I was running a wordpress site at "mydomain.com" with a whmcs installation at mydomain.com/portal. everything was fine. I recently got rid of the wordpress installation and set up a Django website at mydomain.com. The WHMCS installation at mydomain.com/portal is still there. But here is the issue: visiting mydomain.com/portal is giving me 404 error same thing for mydomain.com/portal/admin (404 error) the pages load if i visit mydomain.com/portal/index.php or mydomain.com/portal/login My current .htaccess file in mydomain.com: RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] Header always set Content-Security-Policy "upgrade-insecure-requests;" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/user/mydomain.com" PassengerBaseURI "/" PassengerPython "/home/usr/virtualenv/mydomain.com/3.9/bin/python" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END # DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN <IfModule Litespeed> </IfModule> # DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION END # Newly added text below here, in order to troubleshoot CSS not showing up <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^static/(.*)$ /home/usr/mydomain.com/staticfiles/$1 [QSA,L,NC] </IfModule> <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^media/(.*)$ /home/usr/mydomain.com/blog_images/$1 [QSA,L,NC] </IfModule> <FilesMatch "\.(?i:ico|flv|jpg|jpeg|png|gif|js|css)$"> <IfModule mod_expires.c> ExpiresActive On ExpiresDefault "access plus 1 month" </IfModule> FileETag MTime Size </FilesMatch> I tried adding the below but it did not help. RewriteEngine … -
How can change the primary key in a django model so that other dependent models are also affected and the changes are synced to the postgresql db
I have a django project with a database table that already contains data. The models: class Foo_A(models.Model): field1_pk = models.CharField(max_length=50) field2 . . fieldN_newpk = model.CharField(max_length=50) Data in field1_pk and fieldN_newpk are exactly the same. Lets say I have other models that reference fieldN_newpk as foreign key. I would like to rename a fieldN_newpk in this Foo_A model, without losing any data. This change should also be reflected in my other dependent models. I want to change the primary key from field1_pk to fieldN_newpk I want these changes to be reflected in my postgresql database as well I have seen other answers related to renaming of a model Also Is there a safe way/safe mode to try out these changes/migrations before actually trying on the original codebase -
Synchronizing a Django database with a Realm or Core database in an iOS app
I'm working on an iOS app that needs to synchronize data with a Django backend. The backend uses Django ORM and exposes data through a RESTful API built with Django REST Framework. On the iOS side, I'm using Realm or Core in future as the local database. I need guidance on how to implement synchronization between the Django database and the Realm or Core database in my iOS app. Specifically, I'm looking for advice on the following: How to design the synchronization process to ensure data consistency and integrity. Strategies for fetching data from the Django API and storing it locally in the Realm database. Techniques for handling conflicts between local and server data. Best practices for optimizing synchronization performance and reliability. Recommendations for error handling and retry mechanisms in case of network failures or server errors. Any security considerations or precautions I should take when implementing data synchronization. I would appreciate any insights, sample code, or references to relevant resources that can help me implement robust and efficient data synchronization between my Django backend and iOS app using Realm. Thank you! Some advices who work with