Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to use node modules within a Django app
I developed a web map app using Django. I used Leaflet for the map and I'd like to add some Leaflet plugins that are meant to be installed using npm. I'm new to node (I've only used it in Development during my classes) and have never used it in Production or with Django. I'm wondering if I have to configure anything else in my project or if I can just npm init and then npm install anything. I suppose I'd have to add node_modules to my .gitignore but I'm not sure how should I manage the static files generated by node and how should I import modules into my django templates. I'd be using Node only for front-end stuff, all my back-end is managed by Django. I haven't installed anything yet as I'm afraid I'll break my web. -
How can put my python django project on live?
I have create a project by python django this project work as an documents Archive by uploding the doucments by the admin panle. The problem is that: 1- I want to deploy on my company server. can anyone tell me how to do it because when I have tried the 'python manage.py runsever ipaddressofservermachine, it is working on server machine but it is not working in other laptops. i thought it should have worked but it did not. 2- I want the uploaded file storage not in my :D drive i wanted to be stored in company server I have tried many ways and search in youtube i did not find the way to deploy my project live and make it live and accessible for my employes and make the uploaded file storage not in my :D drive i wanted to be stored in company server -
Remove URL prefix in Jinja + Django
In Django model URLs stored in URL field, so the values are look like "https://example.com/id" In HTML rending with Jinja code should be without https:// prefix like this Can't find any embedded Jinja filters or elegant solution how to remove prefix on the fly without extra coding in DB -
Django view doesn’t recognize the parameter name from template
I am trying to pass two parameters from template (“zn” and “ru”) to filter posts in view. It seems to me, that the variables of both parameters are OK, but not under proper name. The view probably doesn’t recognize which is which. Filtering with parameter “zn” works, but filtering with parameter “ru” doesn’t (see the error statement in picture). enter image description here urls.py: from django.urls import path from . import views urlpatterns = [ ... path("clanky/", views.clanek_vyber, name="clanky_vyber", kwargs={'zn': '', 'ru': ''}), path("clanky/<slug:zn>/", views.clanek_vyber, name="clanky_vyber", kwargs={'ru': ''}), path("clanky/<slug:ru>/", views.clanek_vyber, name="clanky_vyber", kwargs={'zn': ''}), path("clanky/<slug:zn>/<slug:ru>/", views.clanek_vyber, name="clanky_vyber"), views.py: from django.shortcuts import render from django.utils import timezone from django.views import generic from django.core.paginator import Paginator ... from .models import Clanek, Rubrika, Znacka, GalerieObrazku, Hlavni_banner ... def clanek_vyber(request, zn, ru): bannery_1 = Hlavni_banner.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')[:1] clanek_znacka = Clanek.objects.values('znacka') znac = Znacka.objects.filter(id__in=clanek_znacka) rubr = Clanek.objects.distinct('rubrika').order_by('rubrika_id') if (zn!="" and ru!=""): uvodni_clanek = Clanek.objects.filter(znacka__slug=zn).filter(rubrika__slug=ru).order_by('-published_date')[:1] zna = Znacka.objects.get(slug=zn) rub = Rubrika.objects.get(slug=ru) cla_vyb = Clanek.objects.filter(znacka__slug=zn).filter(rubrika__slug=ru).order_by('-published_date')[1:] paginator = Paginator(cla_vyb, 20) # ukáže dvacet dalších článků page_number = request.GET.get("page") page_obj = paginator.get_page(page_number) context = { 'bannery_1': bannery_1, 'uvodni_clanek': uvodni_clanek, 'page_obj': page_obj, 'znac': znac, 'zna': zna, 'zn': zn, 'rubr': rubr, 'rub': rub, 'ru': ru } return render(request, "zentour/clanky.html", context) if(zn!=""): uvodni_clanek = Clanek.objects.filter(znacka__slug=zn).order_by('-published_date')[:1] … -
Why am I getting DoesNotExist for the parent model in save_related
I am firing a celery task in save_related that takes the parent object id and does a get query to obtain the instance for use. Problem is some of the get queries are failing with DoesNotExist. This doesn't make sense to me because the Django docs clearly state that "Note that at this point the parent object and its form have already been saved.". Also why are others not failing? I am about to experiment with what happens when I call super().save_related(...) before the celery task but I don't think that should be an issue because of the note above. Django==4.2.3 -
mock a shell script in Django/DRF test
I tried to make some test on a method in views, but this method call a script shell, this script is write to work in another OS so I need to mocke this. here the test: @patch('check_web_share_file_folder.get_path_from_inode') def test_list_with_search_mocked(self, mock_get_attribute): mock_get_attribute.return_value = 'expected value' request = self.factory.get('/fake-url') force_authenticate(request, user=self.user) view = WebShareFileFolderViewSet.as_view({'get': 'list'}) response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) here the problem, I encounter this error with the test: AttributeError: <function check_web_share_file_folder at 0x00000237FD567708> does not have the attribute 'get_path_from_inode' check_web_share_file_folder.py have of course get_path_from_inode() def get_path_from_inode(inode): std, err, code = popen_wrapper([ 'sudo', 'get_path_from_inode.sh', str(inode) ]) if code != 0: return False return str(std.strip())[1:] -
unique_together in bulk_create
this is my model: class Reminder(models.Model): timestamp = models.DateTimeField() time_frame = models.CharField(default = "5minutes" , max_length=30,choices=[ ("5minutes","5minutes"), ("15minutes","15minutes"), ("30minutes","30minutes"), ("1hour","1hour"), ("4hours","4hours"), ("1day","1day") ]) coin = models.ForeignKey(Coin,on_delete=models.CASCADE) class Meta: unique_together = ["coin","time_frame"] i want to use bulk_create command for create a lot of object from this model. options of bulk_create is update_fields and unique_fields. but i have unique_together fields. what i suppose to do for this code: Reminder.objects.bulk_create(reminders, update_conflicts=True,update_fields=['timestamp'],batch_size=1000) -
Connecting a Django project that is hosted on a Virtual Machine with Nginx and Gunicorn
I'm new to deploying applications. Currently, I'm hosting my Django project on an Ubuntu virtual machine with IP address 192.168.xxx.xxx. It is hosted on a physical service with public IP address of 202.xxx.xxx.xxx (using port 8080). I have gunicorn and nginx installed and incorporated, and they're running properly as sudo systemctl status gunicorn and sudo systemctl status nginx show that they're running with no errors. However, when I try to access the public IP address 202.xxx.xxx.xxx:8080, I'm getting the default Nginx page. As for how I setup my gunicorn and nginx, I followed the guide posted here: https://medium.com/@muhammadali_12976/deploying-django-on-a-local-virtual-machine-virtualbox-with-nginx-and-gunicorn-369f70937913 Here's the gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/home/myProject/myProject.sock [Install] WantedBy=sockets.target Here's the gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myUserName Group=www-data WorkingDirectory=/home/myProject ExecStart=/home/myProject/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/myProject/myProject.sock core.wsgi:application [Install] WantedBy=multi-user.target Here's the contents of my /etc/nginx/sites-available/myProject file server { listen 80; server_name 192.168.xxx.xxx; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myProject; } location / { include proxy_params; proxy_pass http://unix:/home/myProject/myProject.sock; } } Should I have used the public address in server_name or the IP address of the virtual machine where my Django project is hosted? In addition, I also tried changing the port … -
I am getting broken image in a html(cart) page
I am creating an add-to-cart function for my website. I am getting broken images in my cart.html page. So, In cart.html: {% for product_id, item in data.items %} <div class="col-md-12 col-lg-8"> <div class="items"> <div class="product"> <div class="row"> <div class="col-md-3"> <img class="img-fluid mx-auto d-block image" src="{{item.image}}" > <!-- #1 --> </div> <div class="col-md-8"> <div class="info"> <div class="row"> <div class="col-md-5 product-name"> <div class="product-name"> <a href="#">{{item.title}}</a> <div class="product-info"> <div>Display: <span class="value">5 inch</span></div> <div>RAM: <span class="value">4GB</span></div> <div>Memory: <span class="value">32GB</span></div> </div> </div> </div> <div class="col-md-4 quantity"> <label for="quantity">Quantity:</label> <input id="quantity" type="number" value ="1" class="form-control quantity-input"> </div> <div class="col-md-3 price"> <span>{{item.price}}</span> </div> </div> </div> </div> </div> </div> </div> </div> You can see in the #1 that I add the image there. I also created view for add-to-cart function So, in views.py: def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], 'image': request.GET['image'], 'pid': request.GET['pid'], } if 'cart_data_obj' in request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data request.session['total_cart_items'] = len(cart_data) else: request.session['cart_data_obj']=cart_product request.session['total_cart_items'] = len(cart_product) return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items']}) In the 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); … -
Django 5 postgres superuser login fail
I created a Django project SQLite. I decided to move from SQLite to PostgreSQL. All migrations worked. I created the superuser successfully but when I try logging in the admin it says that the user can't be found. this is the users model from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): """ Class for creating custom users. There are 3 user types in this class """ USER_TYPE_CHOICES = ( ('manager', 'Manager'), ('supervisor', 'Supervisor'), ('employee', 'Employee'), ) user_type = models.CharField(max_length=20, choices=USER_TYPE_CHOICES) is_active = models.BooleanField(default=False) name = models.CharField(max_length=255) email = models.EmailField(unique=True) national_id = models.CharField(max_length=20, unique=True) def __str__(self): return self.email # Provide a unique username or remove the unique constraint from email def save(self, *args, **kwargs): if not self.username: self.username = self.name # Use email as username or provide a unique username super().save(*args, **kwargs) I tried logging in the admin. It says the user is not found. I used both email and username to be sure but the user still can't be found. This is pip freeze: pip freeze asgiref==3.7.2 attrs==23.1.0 bcrypt==4.1.2 Django==5.0 django-cors-headers==4.3.1 django-filter==23.5 djangorestframework==3.14.0 djangorestframework-simplejwt==5.3.1 drf-spectacular==0.27.0 Faker==21.0.0 inflection==0.5.1 jsonschema==4.20.0 jsonschema-specifications==2023.11.2 Markdown==3.5.1 mysqlclient==2.2.3 psycopg2==2.9.9 PyJWT==2.8.0 python-dateutil==2.8.2 pytz==2023.3.post1 PyYAML==6.0.1 referencing==0.32.0 rpds-py==0.15.2 six==1.16.0 sqlparse==0.4.4 typing_extensions==4.9.0 uritemplate==4.1.1