Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dead lock found in django transaction with select_for_update function
I have two functions: one for updating data and one for reading data. When they run concurrently in two threads, a deadlock occurs. Does anyone know why? The database's isolation level is set to REPEATABLE-READ. sleep function is used to increase the likelihood of a deadlock occurring. @transaction.atomic() def func_change_data(): print("start") time.sleep(10) boos = Boo.objects.select_for_update(skip_locked=True).filter(pk=xxx) if not changes.exists(): return print("sleep") time.sleep(10) boo = boos.first() boo.stage = 'stage_2' boo.save() print("end") @transaction.atomic() def func__read(): boo = Boo.objects.select_for_update().get( pk=xxx, target_branch='master', stage='stage_1' ) time.sleep(10) print("end sleep") -
How to join attributes of a reverse ManyToManyField in Django ORM
Suppose that these are my models: class Product(models.Model): sku = models.CharField(unique=True) # Something like RXT00887 class Bill(models.Model): customer = models.ForeignKey(Customer) products = models.ManyToManyField(Product) date = models.DateTimeField() Each Product is related to only one Bill or none at all. I am working on a feature which requires me to search through the Products that were bought by a given customer. I am achieving this through: bills = Bill.objects.filter(customer=customer) results = Product.objects.filter(bill__in=bills, sku__icontains=search_str) However, I also need to have some attributes of Bill of each product in the results. For example, I need the bill id and the bill date. So each row in the result should contain all attributes of the product along with two additional attributes: bill_id and bill_date. Is it possible to achieve this is Django by using joins? If so, how? -
Django Form Submission Not Triggering `create_cancel` View
Problem Description: I am implementing an order cancellation feature in my Django application. The process involves displaying a cancellation form (cancel-order.html) using the cancel_order view and processing the form submission with the create_cancel view to update the product_status of CartOrder and CartOrderItems. However, the issue is that the create_cancel view is not being triggered when the form is submitted. No success or error messages are displayed, and no updates are made to the database. Views: Here are the relevant views: def cancel_order(request, oid): sub_category = SubCategory.objects.all() categories = Category.objects.prefetch_related('subcategories').order_by('?')[:4] wishlist = wishlist_model.objects.filter(user=request.user) if request.user.is_authenticated else None nav_category = Category.objects.filter(special_category=True).prefetch_related('subcategories').order_by('?')[:4] order = CartOrder.objects.get(user=request.user, id=oid) products = CartOrderItems.objects.filter(order=order) # Calculate discounts for each product total_old_price = 0 total_price = 0 for item in products: product = item.product # Assuming a ForeignKey from CartOrderItems to Product qty = item.qty # Assuming a quantity field in CartOrderItems total_old_price += (product.old_price or 0) * qty total_price += (product.price or 0) * qty # Calculate total discount percentage if total_old_price > 0: # Prevent division by zero discount_percentage = ((total_old_price - total_price) / total_old_price) * 100 else: discount_percentage = 0 context = { "order": order, "products": products, "sub_category": sub_category, "categories": categories, "wishlist": wishlist, "nav_category": nav_category, "discount_percentage": … -
When I create custom permissions, After saving it automatically deleting the saved permissions in Django
In the Django admin class for the group creation page, I added additional fields. Based on these fields, I need to filter and set the permissions for the group. However, the issue arises in the save method. Although it saves the permissions, I noticed during debugging that the save_m2m() method in the superclass deletes all the assigned permissions class CustomGroupForm(forms.ModelForm): env_name = forms.CharField(max_length=100, required=False) schema_name = forms.CharField(max_length=100, required=False) class Meta: model = Group fields = ['name', 'permissions', 'env_name', 'schema_name'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['permissions'].queryset = Permission.objects.none() def save(self, commit=True): group = super().save(commit=False) # Use the name field as the prefix to filter permissions name = self.cleaned_data.get('name', '') prefix = name logger.info(f'Prefix 1: {prefix}') # Filter permissions using the prefix filtered_permissions = Permission.objects.filter( content_type__app_label__startswith=prefix ) # Save the group first to ensure it has an ID group.save() # Set the filtered permissions group.permissions.set(filtered_permissions) if commit: group.save() return group I expected the custom logic in the save method to correctly save the filtered permissions to the group without being overwritten. Specifically, I wanted the dynamically filtered permissions to persist after saving, without the save_m2m() method clearing them. -
Forbidden (CSRF cookie not set.) Django, Next.js
I am trying to post data to a Django server in order to update a user profile from a Next.js app; I have this similar setting with other routes and they work fine, but here I get the following error: Forbidden (CSRF cookie not set.): /users/api/update-profile/ [15/Dec/2024 20:53:02] "POST /users/api/update-profile/ HTTP/1.1" 403 2855 #settings.py CSRF_COOKIE_HTTPONLY = False # Allow JavaScript to read the CSRF cookie #CSRF_USE_SESSIONS = False CSRF_COOKIE_SAMESITE = 'Lax' CSRF_COOKIE_SECURE = False # Ensure these are set correctly SESSION_COOKIE_SAMESITE = 'Lax' # or 'None' for cross-site CSRF_COOKIE_SAMESITE = 'Lax' # or 'None' for cross-site MIDDLEWARE = [ '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', ] CORS_ALLOW_CREDENTIALS = True #CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOWED_ORIGINS = [ #"http://localhost", #"http://127.0.0.1", "http://localhost:3000" ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] #views.py @login_required def update_profile(request): if request.method == 'POST': user = request.user print('user', user) # Gender validation if 'gender' in request.POST: gender = request.POST.get('gender') if gender in dict(user.gender_choices): user.gender = gender # Username validation if 'username' in request.POST: username = request.POST.get('username') if len(username) <= 50 and not User.objects.exclude(pk=user.pk).filter(username=username).exists(): user.username = username else: return JsonResponse({'status': 'error', 'message': 'Invalid or … -
Django: Cancel Order functionality not updating CartOrder and CartOrderItems instances
I'm building an e-commerce application using Django, and I'm having trouble with the cancel order functionality. When a user cancels an order, I want to update the product_status field of both the CartOrder and CartOrderItems instances to "cancelled". However, the update is not happening, and I'm not seeing any error messages. Here's my code: models.py: class CartOrder(models.Model): # ... product_status = models.CharField(choices=STATUS_CHOICE, max_length=30, default="processing") class CartOrderItems(models.Model): # ... product_status = models.CharField(max_length=200, blank=True, null=True) order = models.ForeignKey(CartOrder, on_delete=models.CASCADE, related_name="cartorderitems") views.py: def create_cancel(request, oid): if request.method == "POST": user = request.user try: # Fetch the CartOrder instance order = get_object_or_404(CartOrder, id=oid) order.product_status = "cancelled" order.save() # Fetch the related CartOrderItems instance order_item = order.cartorderitems.first() order_item.product_status = "cancelled" order_item.save() # Fetch the associated product product = get_object_or_404(Product, pid=order.pid) # Additional product-related operations can be done here, if needed messages.success(request, "Order successfully cancelled.") except Exception as e: messages.error(request, f"An error occurred: {e}") return redirect("core:dashboard") else: messages.error(request, "Invalid request method.") return redirect("core:dashboard") I've tried using order.cartorderitems.first() and CartOrderItems.objects.filter(order=order).first() to get the related CartOrderItems instance, but neither approach is working. Can anyone help me figure out what's going wrong? I've checked the database, and the product_status field is not being updated for either the CartOrder or … -
PDFs with ReportLab in Django. Punjabi Unicode (e.g., ਵਿਰੋਧ ਦੇ ਸਮੇਂ ਫਾਸ਼ੀਵਾਦ) is not displaying correctly. Need font solution
def generate_punjabi_pdf(request): font_path = os.path.join(settings.BASE_DIR, 'static/myapp/css/fonts/Noto_Sans_Gurmukhi/static', 'NotoSansGurmukhi-Regular.ttf') pdfmetrics.registerFont(TTFont('NotoSansGurmukhi', font_path)) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="punjabi_text.pdf"' c = canvas.Canvas(response, pagesize=A4) c.setFont("NotoSansGurmukhi", 16) c.drawString(100, 750, "ਵਿਰੋਧ ਦੇ ਸਮੇਂ ਫਾਸ਼ੀਵਾਦ") c.showPage() c.save() return response -
Django does not detect change to the code when running it with Cursor
My app is based on Django 4.2.16. When I run the app in PyCharm, I see the following message when I run the app: "Watching for file changes with StatReloader". In this setup, changes to HTML files are immediately reflected on the web page after refreshing the browser. The application automatically reloads when I make changes to backend code. However, after switching to Cursor, this behavior is no longer working: I need to manually stop and restart the server for changes (both to HTML and backend code) to take effect. Here is my launch.json configuration in Cursor: { "version": "0.2.0", "configurations": [ { "name": "Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": ["runserver", "localhost:8000"], "django": true, "justMyCode": true, "console": "integratedTerminal", "cwd": "${workspaceFolder}", "pythonPath": "C:/Users/xxx/miniconda3/envs/xxxconda3/python.exe" } ] } I tried to install watchdog with pip but it did not change anything. In my settings.py file, DEBUG = True What can I do ? -
Unable to use psycopg2 with Postgres in Django
As stated in my question, I am now configuring my djagno project to connect with postgres. The issue i am facing is that, when making migrations, it shows me the following error: python manage.py makemigrations Traceback (most recent call last): File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module> import psycopg as Database ModuleNotFoundError: No module named 'psycopg' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\db\backends\postgresql\base.py", line 27, in <module> import psycopg2 as Database File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\psycopg2\__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ...<10 lines>... ) ImportError: DLL load failed while importing _psycopg: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\Code\Ecom\Ecom\backend\manage.py", line 22, in <module> main() ~~~~^^ File "E:\Code\Ecom\Ecom\backend\manage.py", line 18, in main execute_from_command_line(sys.argv) ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^ File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() ~~~~~~~~~~~~~~~^^ File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() ~~~~~~~~~~~~^^ File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() ~~~~~~~~~~~~~~~~~~~~~~~~^^ File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^ File "E:\Coding Apps\Lib\importlib\__init__.py", line 88, in import_module return _bootstrap._gcd_import(name[level:], package, level) ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File … -
How can I turn a PC into a Django web hosting server for use by 50 to 100 users at the same time?
I want to develop an application to manage an organization, which will be used by 50 to 100 users simultaneously. It will work only on a local network and will not connect to the internet. I want the application to be developed using web technologies, not desktop applications, and in Python and Django. How can I turn a PC into a Django web hosting server for use by 50 to 100 users at the same time? What are the requirements for this device? -
Django has a slow import time when using Poetry instead of PIP
I used PIP and poetry in the same project. I also use importtime-waterfall to check import time when running the application (run manage.py file). With case-use Poetry, Django takes more importing time (x2, x3) than case-use PIP. Can you help me explain it? Or give me related documents. Thank you so much !!! -
Python Django Channels provides error on startup on colleagues computer but not on my computer what is going wrong?
I have encountered the following error. The weird thing about this error is that it does not occur on my windows 11 computer, but it only occurs on the windows 11 computer of a colleague and on a remote debian linux server which I have setup specifically to test whether an error like this would also occur on Linux. All computers have the same code (git synced), same libraries (pip freeze and venv), same python version (except the linux server) I cannot figure out the origin and I cannot find any information about a similar error on StackOverflow or any other site. The weird thing is that it does work on my own computer! Traceback (most recent call last): File "/usr/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/usr/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/srv/<redacted>/venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/srv/<redacted>/venv/lib/python3.11/site-packages/daphne/management/commands/runserver.py", line 128, in inner_run application=self.get_application(options), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/srv/<redacted>/venv/lib/python3.11/site-packages/daphne/management/commands/runserver.py", line 153, in get_application return ASGIStaticFilesHandler(get_default_application()) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/srv/<redacted>/venv/lib/python3.11/site-packages/daphne/management/commands/runserver.py", line 31, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'config.asgi' This error is very unhelpful, so after some more debugging we figured out that the origin of the crash comes from: … -
I tried to enable the remove option on cart to remove cart item by adding the some code, result come in following error
I have added the code to enable the remove option on the cart. the following error occurs. Reverse for 'remove_cart_item' with arguments '(2,)' not found. 1 pattern(s) tried: ['cart/remove_cart_item/(?P<product_id>[0-9]+)/(?P<cart_item_id>[0-9]+)/$'] cart.html {% extends 'base.html' %} {% load static %} {% block content %} <!-- ============================ COMPONENT 1 ================================= --> {% if not cart_items%} <h2 class="text-center">Your shopping cart is empty</h2> <br> <div class="text-center"> <a href="{% url 'store' %}" class="btn btn-primary">Continue Shopping</a> </div> {% else %} <div class="row"> <aside class="col-lg-9"> <div class="card"> <table class="table table-borderless table-shopping-cart"> <thead class="text-muted"> <tr class="small text-uppercase"> <th scope="col">Product</th> <th scope="col" width="120">Quantity</th> <th scope="col" width="120">Price</th> <th scope="col" class="text-right" width="200"> </th> </tr> </thead> <tbody> <tr> {% for cart_item in cart_items %} <td> <figure class="itemside align-items-center"> <div class="aside"><img src="{{ cart_item.product.images.url }}" class="img-sm"></div> <figcaption class="info"> <a href="{{ cart_item.product.get_url }}" class="title text-dark">{{cart_item.product.product_name}}</a> <p class="text-muted small"> {% if cart_item.variations.all %} {% for item in cart_item.variations.all %} {{item.variation_category |capfirst }} : {{item.variation_value | capfirst}} <br> {% endfor %} {% endif %} </p> </figcaption> </figure> </td> <td> <!-- col.// --> <div class="col"> <div class="input-group input-spinner"> <div class="input-group-prepend"> <a href="{% url 'remove_cart' cart_item.product.id cart_item.id %}" class="btn btn-light" type="button" id="button-plus"> <i class="fa fa-minus"></i> </a> </div> <input type="text" class="form-control" value="{{cart_item.quantity}}"> <div class="input-group-append"> <form action="{% url 'add_cart' cart_item.product.id %}" method="POST"> … -
Override Django Admin Template In 3rd Party Package?
I am developing a Python package which includes a Django addon app. The package is related to authentication so I wanted to extend the django.contrib.admin login page. Is it possible for my 3rd party package to override another 3rd party package? The template for the login page is under django/contrib/admin/templates/admin/login.html. Which means the template is registered as admin/login.html. I put my overridden template in my package's templates/admin/login.html directory but the template does not get overridden. The order of my package and Django contrib admin in INSTALLED_APPS, template app dirs = true don't seem to change this. -
As I try to add product by selecting its variaitons this error appears NoReverseMatch at /cart/
cart.html <td class="text-right"> <a href="{% url 'remove_cart_item' cart_item.product.id cart_item.id %}" class="btn btn-danger"> Remove</a> </td> urls.py file of the carts app urlpatterns = [ path('', views.cart, name='cart'), path('add_cart/<int:product_id>/', views.add_cart, name='add_cart'), path('remove_cart/<int:product_id>/<int:cart_item_id>/', views.remove_cart, name='remove_cart'), path('remove_cart_item/<int:product_id>/<int:cart_item_id>/', views.remove_cart_item, name='remove_cart_item'), ] views.py file of the carts app def remove_cart_item(request, product_id, cart_item_id): cart = Cart.objects.get(cart_id = _cart_id(request)) product = get_object_or_404(Product, id=product_id) cart_item = CartItem.objects.get(product = product, cart = cart, id=cart_item_id) cart_item.delete() return redirect('cart') -
Single view for multiple paths via URL kwargs
I'm building a simple API listing various plants. Currently, it's limited to filter via a single field like common name, species, etc. My urls.py urlpatterns = [ path('project/family=<str:family>/', views.SpeciesDetail_family.as_view(), name='family'), path('project/species=<str:species>/', views.SpeciesDetail_species.as_view(), name='species') ] And views.py class SpeciesDetail_species(generics.ListAPIView): serializer_class = SpeciesSerializer def get_queryset(self): queryset = Species.objects.filter() species = self.kwargs['species'] if species is not None: queryset = queryset.filter(species__iexact=species) return queryset class SpeciesDetail_family(generics.ListAPIView): serializer_class = SpeciesSerializer def get_queryset(self): queryset = Species.objects.all() family = self.kwargs['family'] if family is not None: queryset = queryset.filter(family__iexact=family) return queryset How can I create a single view for these two paths? So, I just need to parameterize the lookup field (can be family, species, etc.) from the URL like /project/species=PlantSpecies/ or /project/family=PlantFamily/. If I add kwargs to the path like path('project/family=<str:family>/', views.SpeciesDetail_family.as_view(), {'lu_field':'family'}, name='family'), how can I access lu_field in the views? -
Error: Invalid Date/Time Format - The value "0000-00-00 00:00:00.000000" matches the format but is invalid as a date/time in Django validation
`your class EnrollmentModel(models.Model): Semesters=[ (1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four'), (5, 'Five'), (6, 'Six'), (7, 'Seven'), (8, 'Eight'), ] payment_type=( ('Marchent','Marchent'), ('Bkash','Bkash'), ('Rocket','Rocket'), ('Nagad','Nagad'), ('Cash Hand','Cash Hand'), ('Apps','Apps'), ('Upay','Upay'), ) enroll_status=( ('Pending','Pending'), ('Due','Due'), ('Due-Pending','Due-Pending'), ('Complete','Complete'), ('Refunded','Refunded'), ('Due-Paid','Due-Paid'), ('Customized-Paid','Customized-Paid'), ) layer=( ('Full','Full'), ('Department','Department'), ('Non-Department','Non-Department'), ) softmax_student_id = models.CharField(max_length=50, unique=True,null=True, blank=True) student = models.ForeignKey(StudentModel, related_name='student_enroll', on_delete=models.CASCADE,null=True,db_index=True) package = models.ForeignKey(PackageModel, related_name='package_enroll', on_delete=models.CASCADE,null=True,db_index=True) plan = models.ForeignKey(PlanModel, related_name='plans', on_delete=models.CASCADE,null=True,db_index=True) category = models.ForeignKey(CategoryModel, related_name='categories', on_delete=models.CASCADE,null=True,db_index=True) employee = models.ForeignKey(User, related_name='employee_enroll', on_delete=models.CASCADE, null=True,db_index=True) subject=models.ManyToManyField(DepartmentSubjectModel, related_name='dept_subject',blank=True) semester = models.IntegerField(choices=Semesters, null=True, blank=True) course_fee = models.IntegerField(default=0,null=True,blank=True) payable_fee = models.IntegerField(default=0,blank=True,null=True) due_payment_date = models.DateField(default=current_date, null=True, blank=True) extra_amount = models.IntegerField(default=0,null=True, blank=True) sponsored_amount = models.IntegerField(default=0,null=False, blank=True) initial_paid = models.IntegerField(default=0,null=False, blank=True) payment_type = models.CharField(max_length=100, choices=payment_type, blank=True, null=True) payment_number = models.CharField(max_length=100, null=True, blank=True) is_due_enrollment = models.BooleanField(default=False) invoice_number = models.CharField(max_length=100, null=True, blank=True) course_note = models.TextField(max_length=500, null=True, blank=True) status = models.CharField(max_length=20, choices=enroll_status, default='Pending') package_layer=models.CharField(max_length=100,null=True,blank=True,choices=layer) created_at = models.DateTimeField( default=timezone.now,db_index=True,null=True, blank=True) updated_at=models.DateTimeField(auto_now=True) is_old_student= models.BooleanField( default=False, null=True, blank=True) is_message_send= models.BooleanField( default=False,null=True, blank=True) is_service_satisfied= models.BooleanField( default=False,null=True, blank=True) class Update_EnrollmentSerializer(serializers.ModelSerializer): # package = serializers.PrimaryKeyRelatedField(queryset=PackageModel.objects.all(), required=True) # student = serializers.PrimaryKeyRelatedField(queryset=StudentModel.objects.all(), required=True) subject = serializers.PrimaryKeyRelatedField(queryset=DepartmentSubjectModel.objects.all(), required=False, many=True) created_at = serializers.DateTimeField( input_formats=[ '%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%S.%f', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d', '%Y-%m-%d %I:%M %p' # Handle "12:00 AM" case ], required=False ) class Meta: model = EnrollmentModel fields = … -
Django / Python Error: Could not parse the remainder: ' Server' from 'SQL Server'
Im getting this error when rendering an HTM file on my Django instance. It is thrown in a py-script tag. However, if I drop the following code into a .py file and run/debug it in either Powershell or VSCode, its just fine. I just started learning Python and Django and its neat. It took me a couple of days to get it set up and running, and I like it very much. Anyway Code: <py-script> print("booyaaaa") import pyodbc import ctypes connectionString = "DRIVER={{SQL Server}};SERVER=###;DATABASE=###;UID=##;PWD=###" conn = pyodbc.connect(connectionString) SQL_QUERY = """ SELECT TOP 55 * FROM dbo.tbl### ORDER BY ID DESC """ cursor = conn.cursor() cursor.execute(SQL_QUERY) records = cursor.fetchall() recordString = "" for r in records: recordString += str(r.DonorID) + "\n" print(recordString) </py-script> Error: Environment: Request Method: GET Request URL: http://localhost/ Django Version: 5.0.10 Python Version: 3.13.1 Installed Applications: ['whitenoise.runserver_nostatic', 'myDjangoProj', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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'] Template error: In template C:\Users\marlon\myDjangoProj\myDjangoProj\templates\index.htm, error at line 18 Could not parse the remainder: ' Server' from 'SQL Server' 8 : <script defer src="https://pyscript.net/alpha/pyscript.js"></script> 9 : 10 : <title>PyScript Demo</title> 11 : </head> 12 : <body> 13 : <py-script> 14 : print("booyaaaa") 15 : … -
Django model-objects permission per logged user/owner?
I've got django model , that has creator field = logged user. class MyModel(models.Model): creator = models.ForeignKey(User, on_delete=models.SET_NULL ) It works fine. Then, in all my views (lists, create update, delete etc)... I would like to allow only the owner (creator) to be able to view and modify his objects. Do I need to check it manually in the beginning of every view, ie.. check the creator of the object to be deleted (for example) if equals logged user, or is there any more elegant way? -
Django Oauth Toolkit with custom User model
a question here. I want to use https://django-oauth-toolkit.readthedocs.io/en/latest/index.html. But I want the authentication to use different user model (not the settings.AUTH_USER_MODEL). Is that possible ? All answers I found just said, to set the AUTH_USER_MODEL to my custom model - but this is not what I want. Regular admin authentication would use default model of course. Thanks. -
How do I pass an item and an associated formset from the view to the template in Django?
I understand how to pass multiple items in the views to the template, you just pass multiple items in the context. I'm trying to learn to build a checklist app for learning and to have a formset for links associated to each item to learn. So you can like save multiple youtube instructional links to each item. But let's say that I am passing query of items over. And for each item has a formset created for it. How do I pass over the associated formset over with the item? Thru using chatgpt and google, I've come up with this def currentchecklist(request): items = Item.objects.filter(user=request.user, datecompleted__isnull=True) courses = request.user.checklist_courses.all() LinkFormSet = inlineformset_factory(Item, Link, fields=('url',), extra=1) formsets = [] for item in items: formsets.append((item, LinkFormSet(instance=item))) return render(request, "BJJApp/currentchecklist.html", {"items": items,"courses": courses, "formsets": formsets}) and then in the template, I have this {% for item, formset in formsets %} <div class="formset" id="linkform-{{ item.id }}" style="display: none;"> <label for="title">Links for {{ item.title }}</label> {{ formset.as_p }} </div> This code works so far to display the formset, I'm next working on saving the links. I just wanted to ask, is this the best way to access the item and associated formset? By using the … -
Django: Context not available when rendering a djang_tables2 table
I have a django_tables2 class: class DeviceTable(tables.Table): class Meta: template_name = "main/tables/bootstrap_custom.html" Then a base class: class BaseClass(SingleTableMixin, LoginRequiredMixin, PermissionRequiredMixin, FilterView): def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) context["foo_base"] = "bar_base" return context And a view class: class ViewClass(BaseClass): table_class = DeviceTable def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) context["foo_view"] = "bar_view" return context When rendering the "bootstrap_custom.html", the context doesn't contain the expected information. Neither "{{ foo_base }}" nor "{{ foo_view }}" are available in the context. Any idea? -
How to properly set up django channels and websocket
I'm trying to implement websocket and django channels. On frontend I have react and on backend django. I've installed channels and added it to INSTALLED_APPS in settings and I also added to settings.py ASGI_APPLICATION = 'VideoScreen.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } The routing is as follows: websocket_urlPattern = [ path("ws/device-key/", DeviceCodeConsumer.as_asgi()), ] application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AuthMiddlewareStack(URLRouter(websocket_urlPattern)), } ) channel_routing = {"http.request": StaticFilesHandler()} And DeviceCodeConsumer is as follows: class DeviceCodeConsumer(WebsocketConsumer): def connect(self): self.group_name = 'device_key' async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) print(f"Added to group {self.group_name}") # Debugging message # Accept the WebSocket connection self.accept() def receive(self, text_data): # Handle incoming JSON messages if needed print('RECIEVED: ' + text_data) text_data_json = json.loads(text_data) message = text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.group_name, { 'type': 'update_device_key', 'message': message } ) def update_device_key(self, event): message = event['message'] self.send(text_data=json.dumps({ 'type': 'update_device_key', 'message': message })) Thus I create group with name device_key and I want to add a message to that group when some code executes in django view and to notify the frontend about it. The view in django that I have is as follows: @login_required def device_edit_view(request, device_id): if device_id <= 0: device = Device() else: device = Device.objects.get(pk=device_id) if request.method == "POST": … -
Assistance Required: Vercel 404 Error While Deploying Django Application
I am trying to deploy a Django application on Vercel, but I keep encountering a 404: NOT_FOUND error. Below is a summary of my setup and the configuration I have used: vercel.json Configuration { "version": 2, "builds": [ { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } }, { "src": "notes/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } } ], "routes": [ { "src": "/(.*)", "dest": "notes/wsgi.py" }, { "src": "/static/(.*)", "dest": "/static/$1" } ] } What I Have Tried Verified that wsgi.py is properly configured and callable. Confirmed that static files have been collected and are stored in the staticfiles_build directory. Checked the routes and rewrites section of the vercel.json file to ensure proper mapping. Problem Description After deployment, I receive the 404: NOT_FOUND error when accessing the app. However, the build process completes successfully, and the deployment URL is generated. The Django application works perfectly on my local machine, but it seems something is missing in my deployment configuration for Vercel. Question What changes or additions do I need to make in my vercel.json file or deployment process to resolve this issue? Any guidance or suggestions would be greatly appreciated! Github link: https://github.com/Arnav613Gupta/Notes-Api.git vercel url … -
What is the best way to save preload data to prevent N+1 in NestedModelAdmin
We have an N+1 problem that our NestedModelAdmin has to deal with multiple databases. After working around it, we decided to fetch it beforehand in get_queryset. The drawback is that it will fetch all records in that table. class PODOrderAdmin(nested_admin.NestedModelAdmin): list_display = ('order_id', 'get_order_name', 'get_order_type', 'get_suppliers') def get_queryset(self, request): order_filter = request.GET.get('order') qs = super().get_queryset(request).prefetch_related( Prefetch( 'podlineitem_set', queryset=PODLineItem.objects.select_related('line_item') ), ).select_related('order') self.suppliers = list(PodSupplier.objects.only('id', 'name')) return qs def get_suppliers(self, obj): # Filter the pod_line_items by pod_order.id to match obj.id supplier_ids = [line_item.supplier_id for line_item in obj.podlineitem_set.all()] filtered_suppliers = [] if hasattr(self, 'suppliers'): filtered_suppliers = [supplier for supplier in self.suppliers if supplier.id in supplier_ids] else: filtered_suppliers = PodSupplier.objects.filter(id__in=supplier_ids) if filtered_suppliers: supplier_names = [(supplier.name,) for supplier in filtered_suppliers] return format_html_join('\n', '{}<br>', supplier_names) return None get_suppliers.short_description = 'Suppliers' admin.site.register(PODOrder, PODOrderAdmin) We tried to use queryset super().get_queryset(request) to reduce the number of records but it's not working, after checking some documents, it turns out get_queryset is called BEFORE paging happen qs = super().get_queryset(request).prefetch_related('podlineitem_set').select_related('order') pod_order_ids = qs.values_list('id', flat=True) self.pod_line_items = list(PODLineItem.objects.filter(pod_order_id__in=pod_order_ids)) self.suppliers = list(PodSupplier.objects.filter(id__in=[pod_line_item.supplier_id for pod_line_item in self.pod_line_items])) Another solution is to mimic paging but it only make code more complicated page = int(request.GET.get('p', 0)) limit = self.list_per_page subqueryset = queryset[page * limit: (page + 1) …