Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx not loading django static files
I'm having difficulties making a minimal nginx+gunicorn+django static files work properly, here are further details: Here's the nginx site config: server { listen 80; server_name SERVER_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias PATH/TO/PROJECT/static/; } location / { include proxy_params; proxy_pass http://SERVER_IP:8000; } } I run django with gunicorn using gunicorn -c gunicorn.conf.py WSGI_FILE using this config: command = 'PATH/TO/PROJECT/venv/bin/gunicorn' pythonpath = 'PATH/TO/PROJECT' bind = 'SERVER_IP:8000' workers = 3 Also to note I've added proper STATIC variables to django settings.py and did collectstatic. Seems like to be nginx config problem but couldn't find anything online yet. I've also tried giving group access to nginx(user www-data) for the static files. But I still believe it could be problem of similar type. -
Django View: `DoesNotExist` error when trying to edit a product
I'm trying to create an edit product feature in my Django application, but I'm running into a DoesNotExist error when I try to access the edit product page. Here's my view function: @login_required def edit_product(request, pid): product = Product.objects.get(pid=pid) if request.method == "POST": form = AddProductForm(request.POST, request.FILES, instance=product) if form.is_valid(): new_product = form.save(commit=False) new_product.user = request.user # assuming there is a user field in the Product model new_product.save() form.save_m2m() # Save many-to-many relationships return redirect("vendorpannel:dashboard") else: # Print form errors for debugging print(form.errors) else: form = AddProductForm(instance=product) context = { "form": form, "product": product, } return render(request, "vendorpannel/edit-product.html", context) When I try to access the edit product page, I get the following error: DoesNotExist at /vendorpannel/edit_product/11 Product matching query does not exist. I've checked my database, and the product with the specified pid exists. I'm not sure what's causing this error. Can anyone help me identify the issue and suggest a solution? if you need my template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Edit Product</title> <!-- Bootstrap CSS --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> <style> body { padding-top: 50px; } .container { max-width: 600px; margin: auto; } .form-group label { font-weight: bold; } .form-actions { text-align: right; … -
Django Summernote image URL issue
I'm using Summernote in my Django project. The editor works fine. The image loads in the editor and appears in the media folder, but after saving the image disappears and an empty img tag appears. I made a few attempts looking for solutions but without success. models.py; from django.db import models from django.utils.translation import gettext_lazy as _ from unidecode import unidecode from django_summernote.fields import SummernoteTextField from django.urls import reverse from articles.models.category_model import ArticleCategory from django.utils.text import slugify import re from PIL import Image import os from django.conf import settings from meta.models import ModelMeta from datetime import datetime class Article(ModelMeta, models.Model): title = models.CharField(_('Title'), max_length=255) category = models.ForeignKey(ArticleCategory, verbose_name=_('Category'), on_delete=models.CASCADE, related_name='articles') slug = models.SlugField(_('Slug'), max_length=255, unique=True, blank=True) featured_image = models.ImageField(_('Featured Image'), upload_to='articles/', blank=True, null=True) meta_description = models.CharField(_('Meta Description'), max_length=160, blank=True) content = SummernoteTextField(_('Content')) created_at = models.DateTimeField(_('Created At'), auto_now_add=True) updated_at = models.DateTimeField(_('Updated At'), auto_now=True) created_by = models.ForeignKey('users.CustomUser', verbose_name=_('Created By'), on_delete=models.CASCADE, related_name='articles') hashtags = models.ManyToManyField('Hashtag', related_name='hashtag_articles', blank=True) is_published = models.BooleanField(_('Is Published'), default=True) publish_date = models.DateTimeField(_('Publish Date'), default=datetime.now) is_featured = models.BooleanField(_('Is Featured'), default=False) is_trending = models.BooleanField(_('Is Trending'), default=False) is_sponsored = models.BooleanField(_('Is Sponsored'), default=False) _metadata = { 'title': 'title', 'description': 'meta_description', 'image': 'image_url', } _schema = { 'type': 'Article', 'name': 'title', 'description': 'meta_description', 'image': 'image_url', … -
is there is anyone who can help me fix this django error?
im getting this error while running python manage.py runserver in terminal, pls help to fix this {C:\Users\sumit\AppData\Local\Programs\Python\Python312\python.exe: can't open file 'C:\Users\sumit\PycharmProjects\pythonProject1\manage.py': [Errno 2] No such file or directory(.venv) PS C:\Users\sumit\PycharmProjects\pythonProject1> cd projectintern(.venv) PS C:\Users\sumit\PycharmProjects\pythonProject1\projectintern> python manage.py makemigrationsTraceback (most recent call last):File "C:\Users\sumit\PycharmProjects\pythonProject1\projectintern\manage.py", line 22, in <module>main()File "C:\Users\sumit\PycharmProjects\pythonProject1\projectintern\manage.py", line 18, in mainexecute_from_command_line(sys.argv)File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\management_init_.py", line 442, in execute_from_command_lineutility.execute()File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\management_init_.py", line 436, in executeself.fetch_command(subcommand).run_from_argv(self.argv)File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argvself.execute(*args, **cmd_options)File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\management\base.py", line 454, in executeself.check()File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\management\base.py", line 486, in checkall_issues = checks.run_checks(^^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checksnew_errors = check(app_configs=app_configs, databases=databases)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\checks\urls.py", line 14, in check_url_configreturn check_resolver(resolver)^^^^^^^^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\checks\urls.py", line 24, in check_resolverreturn check_method()^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\urls\resolvers.py", line 519, in checkfor pattern in self.url_patterns:^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\utils\functional.py", line 47, in getres = instance.dict[self.name] = self.func(instance)^^^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\urls\resolvers.py", line 738, in url_patternspatterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)^^^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\utils\functional.py", line 47, in getres = instance.dict[self.name] = self.func(instance)^^^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\urls\resolvers.py", line 731, in urlconf_modulereturn importlib._bootstrap>", line 488, in _call_with_frames_removedFile "C:\Users\sumit\PycharmProjects\pythonProject1\projectintern\myapp\urls.py", line 5, in <module>path('', views.index())^^^^^^^^^^^^^TypeError: index() missing 1 required positional argument: 'render'} solution of this error -
How to Create a New Database and Run Migrations Dynamically in Django?
I have an application where I need to create a new database and run migrations to create tables. Here is my current implementation: def create_database(db_name): with connection.cursor() as cursor: try: cursor.execute(f"CREATE DATABASE IF NOT EXISTS {db_name}") return True except Exception as e: print(f"Error creating database {db_name}: {str(e)}") return False The code above successfully creates the database. def run_migrations(db_name, app_names): new_db_settings = copy.deepcopy(settings.DATABASES['default']) new_db_settings.update({ 'NAME': db_name, }) settings.DATABASES['default'] = new_db_settings try: with TemporaryOverrideSettings({'default': new_db_settings}): call_command('makemigrations', app_names) call_command('migrate', app_names, database=db_name) except Exception as e: # Handle potential errors gracefully print(f"Error encountered while checking migrations: {e}") The run_migrations function is intended to run the migrations. The makemigrations command runs successfully, but the migrate command does not work for the new database. My requirement is to always create the database and run migrations on each request. However, since there might not be new changes, the migrations might not need to run every time. Issue: The migrate command does not work as expected for the new database after running makemigrations. Questions: How can I ensure that the migrate command runs correctly on the new database? Is there a better approach to handle dynamic database creation and migrations in Django? Any help or suggestions would be … -
Get "RuntimeError: Event loop is closed" while running pytest in django channels
I wrote a test for my websocket connection. Here is my pytest code. import pytest from channels.testing import WebsocketCommunicator from django.contrib.auth import get_user_model from rest_framework_simplejwt.tokens import AccessToken from dashboard.token_auth import TokenAuthMiddleware from channels.routing import URLRouter from django.urls import path from dashboard.consumers import DashboardConusmer UserModel = get_user_model() @pytest.fixture @pytest.mark.django_db def access_token(): user = UserModel.objects.create_user(email='hello@hello.com', password='hello@hello1') access = AccessToken.for_user(user) return str(access) @pytest.fixture(autouse=True) @pytest.mark.django_db def set_channel_layer(settings): settings.CHANNEL_LAYERS = {"default": {"BACKEND": "channels.layers.InMemoryChannelLayer"}} @pytest.mark.django_db @pytest.mark.asyncio class TestDashboard: pytestmark = pytest.mark.django_db async def test_connection(self, access_token): application = TokenAuthMiddleware( URLRouter([path("ws/dashboard/", DashboardConusmer.as_asgi())])) url = f"ws/dashboard/?token={access_token}" communicator = WebsocketCommunicator(application, url) connected, _ = await communicator.connect() assert connected await communicator.disconnect() It shows RuntimeError: Event loop is closed Error code is Task was destroyed but it is pending! task: <Task cancelling name='Task-2' coro=<ProtocolTypeRouter.__call__() running at /usr/local/lib/python3.10/site-packages/channels/routing.py:62> wait_for=<Future finished result=None>> Exception ignored in: <coroutine object ProtocolTypeRouter.__call__ at 0x7f139df44f20> Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/channels/routing.py", line 62, in __call__ File "/home/app/web/dashboard/token_auth.py", line 37, in __call__ File "/usr/local/lib/python3.10/site-packages/channels/routing.py", line 132, in __call__ File "/usr/local/lib/python3.10/site-packages/channels/consumer.py", line 94, in app File "/usr/local/lib/python3.10/site-packages/channels/consumer.py", line 58, in __call__ File "/usr/local/lib/python3.10/site-packages/channels/utils.py", line 55, in await_many_dispatch File "/usr/local/lib/python3.10/asyncio/base_events.py", line 753, in call_soon File "/usr/local/lib/python3.10/asyncio/base_events.py", line 515, in _check_closed RuntimeError: Event loop is closed Task was destroyed but it is … -
is there a way in django to select data from tables when one is a backwards link?
I've got tables as shown below. I know I can do the following: value = Zero.objects.select_related('one').select_related('two') three = value.two.three_set.all() But that results with the data spread across two queries. is there a way to combine all that into one statement? I could probably do it with raw sql but I'd rather not. -
I am having an issue uploading an image with Django
I am currently working my way through a django project and am having trouble working with MEDIA and uploading an graph image. Inside settings.py, I have added the below code. MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')` HomePage.html: <img src="{{ MEDIA_URL }}image.png" alt="Uploaded Image" style="max-width: 100%; height: auto;"> HomePage->urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Relative Path from the html file to the image: media/graph/upload/image.png I get the error Not Found: /graph/upload/image.png. Main Project --App ----settings.py --HomePage ----HomePage.html ----urls.py --media ----graph ------upload --------image.png Thank you for all your help! Let me know if you need anymore of the code, I just didn't want to make this super long if this is a simple error. I've also tried hardcoding the path to the directory and that did not work either so I think I am misunderstanding something with Django. -
dividing aggregate expressions (Count / Count) results to zoro, no matter what
here's a code snippet of the problem #multiplication works fine drivers.annotate( completed_orders_percentage=( Count('orders', filter=Q(orders__rejected=False), distinct=True) * Count('orders', distinct=True) ) * 100 , ) #addition works fine drivers.annotate( completed_orders_percentage=( Count('orders', filter=Q(orders__rejected=False), distinct=True) + Count('orders', distinct=True) ) * 100 , ) #subtraction works fine drivers.annotate( completed_orders_percentage=( Count('orders', filter=Q(orders__rejected=False), distinct=True) - Count('orders', distinct=True) ) * 100 , ) #diving not working (returns 0) drivers.annotate( completed_orders_percentage=( Count('orders', filter=Q(orders__rejected=False), distinct=True) / Count('orders', distinct=True) ) * 100 , ) i couldnt find anything useful in the docs, i thought that it might be due to type of the return so i tried to wrappe it in ExeprisionWrapper with output_field=FloatField() but still the same! -
Celery Worker Fails with AttributeError: 'NoneType' object has no attribute 'Redis' in Django Project
I'm working on a Django project where I need to send periodic emails using Celery. My environment is set up on Ubuntu, and I have Redis installed both on my system and within my virtual environment. Command: celery -A main worker -l info However, when I try to run the Celery worker, I encounter the following error: Traceback (most recent call last): File "/home/osama/Projects/send_email_with_celery/.venv/bin/celery", line 8, in <module> sys.exit(main()) ^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) ^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/bin/celery.py", line 236, in main return celery(auto_envvar_prefix="CELERY") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/click/core.py", line 1157, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/click/core.py", line 1078, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/click/core.py", line 1688, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/click/core.py", line 1434, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/click/core.py", line 783, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/click/decorators.py", line 33, in new_func return f(get_current_context(), *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/bin/base.py", line 135, in caller return f(ctx, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/bin/worker.py", line 348, in worker worker = app.Worker( ^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/worker/worker.py", line 98, in __init__ self.setup_instance(**self.prepare_args(**kwargs)) File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/worker/worker.py", line 119, in setup_instance self._conninfo = self.app.connection_for_read() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/app/base.py", line 821, in connection_for_read return self._connection(url or self.conf.broker_read_url, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/app/base.py", line … -
Django Nested Serializers witj Foreign Field
I am trying to post this json request through postman { "name":"Someones order", "date_due": "2024-06-23T15:52:59Z", "customer":3, "orderItem":[{ "item":1, "count":1 }] } I have implemented my models like so. class Item(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=6, decimal_places=2) bakery = models.ForeignKey(Bakery,on_delete=models.CASCADE,related_name='items') def __str__(self): return f'{self.name}' class Order(models.Model): name = models.CharField(max_length=255) bakery = models.ForeignKey(Bakery,on_delete=models.CASCADE,related_name='orders') customer = models.ForeignKey(Customer,on_delete=models.CASCADE,related_name='orders') date_created= models.DateTimeField(auto_now_add=True) date_due = models.DateTimeField() date_updated = models.DateTimeField(auto_now=True) #order_item = models.OneToOneField(OrderItem, on_delete=models.CASCADE,related_name='item_orderitems') def __str__(self): return f'{self.name}' class OrderItem(models.Model): bakery = models.ForeignKey(Bakery,on_delete=models.CASCADE,related_name='order_items') count = models.IntegerField() item = models.ForeignKey(Item, on_delete=models.CASCADE,related_name='item_orderitems') order = models.OneToOneField(Order, on_delete=models.CASCADE,related_name='orderitems') def __str__(self): return f'{self.name}' Serializer is implemented as class OrderItemCreateSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['item','count'] class OrderCreateSerializer(serializers.ModelSerializer): orderItem=OrderItemCreateSerializer(many=True) class Meta: model = Order fields = ("name","date_due","customer","orderItem") def create(self, validated_data): print("create") print(validated_data) itemid=validated_data.pop("orderItem") print(itemid) bakery=self.context['request'].user.bakery customer=validated_data.pop("customer") print(customer) print("validated_data") print(validated_data) order=Order.objects.create(bakery=bakery,customer=customer,**validated_data) print("create 4") for items in itemid: print("create 5") OrderItem.objects.create(bakery=bakery,order=order,**items) print("create 6") print("returning") return order When I make the post request i get Got AttributeError when attempting to get a value for field orderItem on serializer OrderCreateSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Order instance. Original exception text was: 'Order' object has no attribute 'orderItem'. I understand that Order model do not … -
Django view to redirect to same url with different parameter?
I've got django app with a views (urls), that show different lists for different locations: path('ItemList/<int:locationId>/', views.ItemList, name="ItemList"), path('SomethingList/<int:locationId>/', views.SomethingList, name="SomethingList"), and then in a template I've got a menu, when I can switch between locations, ie. being in -- ItemList/2/ I can switch to location with different Id or being in SomethingList/4/ I can switch to location with different Id To switch location, I've got a method (which obviusly is incorrect): def setLocation (request, newLocationId): return redirect(request.META['HTTP_REFERER'], locationId = newLocationId) but how can I do it, to get the current location url like: ItemList/2/ and redirect it to ItemList/4/ (ie. to different id?) -
How can I link user input data from one field in a Django model, to another field in the same model?
Apologies if this is a stupid question or if my terminology is not quite right. I'm very new to Django and programming! I'm looking to build a quoting tool for my website, which will basically be a form that clients fill in, which will create an instance of a "quote" model, and the actual quote value will be automatically calculated and stored as part of the model instance, based on the data input by the user. I've looked around online but I'm really struggling to find a simple explanation of how a model field can be validated and/or automatically calculated and stored, based on data inputs from earlier fields. My first hurdle is below: class Quote(models.Model): total_plots = models.IntegerField(default=1) total_types = models.IntegerField(default=(total_plots),validators=[MinValueValidator(1),MaxValueValidator(total_plots)]) So what I'm trying and failing to do here is initially set the default value for total_types, to the same as what the user has input for total_plots. I want to then allow the user to change the value of total_types, but it can't be greater than what they have entered for total_plots, so I need to grab the value they enter for total_plots and use it to restrict what they are able to enter for total_types. The … -
Why raising serializers.ValidationError() is causing UnicodeDecodeError?
I am creating a django rest API(with a ImageField) and it is working fine. But I want to add some validations to some CharFields fields. I noticed some unicodeDecoderError while added a validator or simply raising a validation error. Spent quite a lot of time trying to solve it. Any help will be appreciated. Here is my serializers.py file from rest_framework import serializers from .models import * def validate_phone(phone_number: str): print(phone_number) if not (phone_number.startswith(("6", "7", "8", "9"))): raise serializers.ValidationError( {"phone": "phone number must startwith digits from 6-9 !!!"}) if not phone_number.isnumeric(): raise serializers.ValidationError( {"phone": "phone number should contain digits only !!!"}) if len(phone_number) != 10: raise serializers.ValidationError( {"phone": "phone number must contain only 10 digits !!!"}) class StudentSerializer(serializers.ModelSerializer): start_date = serializers.DateField(format='%d %B %Y') phone = serializers.CharField(max_length=10, validators=[validate_phone]) class Meta: model = Student fields = '__all__' Raising a validation error is resulting a UnicodeDecoderError. Working fine otherwise. This is my models.py file from django.db import models class Student(models.Model): ... phone = models.CharField(max_length=10) ... start_date = models.DateField() profile_picture = models.ImageField(upload_to='profile/', blank=True) ... I am sending the data using javascript fetch API with FormData() which handles the file formatting and encoding. Here is the javascript file: const form = document.querySelector("form"); form.addEventListener("submit", (e) => … -
How to show/hide a bootstrap spinner on a button WITHOUT jQuery?
How can I show spinner on a button after clicking, disabled the button after clicking? I am using Django templates. I do not want to use jQuery at all. Looked at many other posts, most of them depend on jQuery. <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"> <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script> Template submit button <!-- Submit button --> <div class="d-grid gap-2 col-6 mx-auto"> <input type="submit" value="Sign in" class="btn btn-primary btn-block mb-4" /> </div> Bootstrap example <button class="btn" type="button"> <span class="spinner-border spinner-border-sm" role="status"></span> Loading... </button> -
Django & Pycharm keep giving me URL error
I keep geeting this Login although in my project I make zero mention of log inPage not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/login/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, login/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. my actual code project django-admin mysite settings""" Django settings for mysite project. Generated by 'django-admin startproject' using Django 4.1.3. from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "secret code" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. July 04, 2024 - 17:36:23 Django version 4.2.13, using settings 'mysite.settings' Starting … -
Performance Error with Django Import/export
I am experiencing a performance issue with Django import-export in my production environment. When importing a spreadsheet with around 3k rows, the process ends up with an Internal Server Error However, when I run the tests in the production environment, despite the delay, it successfully completes the upload of the rows. Am I missing any configuration, or does it really need to be faster to work correctly? Here are my configurations: class AtivosAssetAllocationResource(resources.ModelResource): class Meta: use_bulk = True batch_size = 1000 model = AtivosAssetAllocation fields = ('id', 'grupo', 'ticker', 'siglacmd', 'ativo', 'nomeComercial', 'conservador', 'moderado', 'agressivo', 'descricao', 'aprovado', 'classe', 'subclasse', 'range', 'previdencia') And for reference, here is the model: class AtivosAssetAllocation(models.Model): ticker = models.CharField(max_length=40, unique=True) siglacmd = models.CharField(max_length=20, blank=True, null=True) ativo = models.CharField(max_length=100) nomeComercial = models.CharField(max_length=100, blank=True, null=True) conservador = models.FloatField(blank=True, null=True) moderado = models.FloatField(blank=True, null=True) agressivo = models.FloatField(blank=True, null=True) descricao = models.TextField(blank=True, null=True) classe = models.CharField(max_length=100, blank=True, null=True) subclasse = models.CharField(max_length=100, blank=True, null=True) range = models.FloatField(blank=True, null=True) previdencia = models.BooleanField(default=False) aprovado = models.BooleanField(null=True, blank=True, default=None) def __str__(self): return self.ativo Previously, the import was done normally, but due to this error, I ended up adding the method bulk use_bulk = True batch_size = 1000 And in settings.py: # Import Export IMPORT_EXPORT_USE_TRANSACTIONS … -
Forbidden (CSRF cookie not set.) Django 4.1
I was trying to add a chatbot (dialogflow) to my current Django webpage. However, I encounter a problem. I get this message: Forbidden (CSRF cookie not set.): /. My first attempt at finding out the problem was to comment the following line in settings.py: django.middleware.csrf.CsrfViewMiddleware And got this message: Method Not Allowed (POST) So I thought, that my post routing was wrong. I was testing using Postman: Then got the following result: I will add my github with how the files are exactly located. My guess is that my routing is wrong but the other files work perfectly.food_website -
Resolve http URI for azure data lake
For the current PR, I am not able to successfully create the pre-signed urls, any suggestions? - name: stage request: method: GET url: '{django_live_url}/api/projects/{project_pk}/next' response: json: data: image_url: !re_match "/tasks/\\d+/presign/\\?fileuri=YXp1cmUtYmxvYjovL3B5dGVzdC1henVyZS1pbWFnZXMvYWJj" status_code: 200 This test above fails, the endpoint returns "azure-spi://<path/to/file>" instead of "/tasks/\d+/presign/?fileuri=YX..." -
Django Auth LDAP - Group search not working
I've been trying to get LDAP to integrate to Django without success for about a week. My problem comes on the group search. It simply does not give me any output, even though everything is correct. The user search works fine. Here's the settings.py file: AUTH_LDAP_SERVER_URI = 'xx' AUTH_LDAP_BIND_DN = 'xx' AUTH_LDAP_BIND_PASSWORD = 'xx' AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=xx,dc=xx,dc=xx", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'ou=xx,dc=xx,dc=xx', ldap.SCOPE_SUBTREE, "(objectClass=group)" ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="CN") The server output: Invoking search_s('ou=xx,dc=xx,dc=xx', 2, '(sAMAccountName=luiz.moura)') search_s('ou=xx,dc=xx,dc=xx', 2, '(sAMAccountName=%(user)s)') returned 1 objects: cn=luiz moura,ou=xx,ou=xx,ou=xx,ou=xx,dc=xx,dc=xx Binding as cn=luiz moura,ou=xx,ou=xx,ou=xx,ou=xx,dc=xx,dc=xx Populating Django user luiz.moura The user is saved on the database, but no group information. Worth to mention i've tried a lot of stuff on the AUTH_LDAP_GROUP type. These are my AD configs: dn: CN=xx,OU=xx,OU=xx,OU=xx,OU=xx,OU=xx,DC=xx,DC=xx objectClass: top objectClass: group member: CN=xx,OU=xx,OU=xx,OU=xx,OU=xx,OU=xx,DC=xx,DC=xx ... -
TimedRotatingFileHandler creates logs at random timestamps
{‘file’: {‘level’: ‘DEBUG’, ‘class’: ‘logging.handlers.TimedRotatingFileHandler’, ‘filename’: os.path.join(LOG_PATH, ‘temp.log’), ‘when’: ‘s’, ‘interval’: 10, #rotates/creates new logs every 10 seconds } I have the above piece of code as a handler in my LOGGING configuration. The logging doesn’t work as expected, new log files are created at random timestamps and not every 10 seconds. How to resolve this. My project runs in a docker container and there are many files that use logging. As additional info LOG_PATH is in the /opt directory of linux filesystem -
How to Implement a Guest Login in Django REST Framework
I currently have a backend setup where users can register by providing an email, name, and password. These fields are required for registration. I want to implement a guest login feature where a guest account is deleted when the browser is closed or the guest logs out. How should I proceed to create a guest account, and what information should I include for the guest account (email, name, password)? Here is the current code: class CreateUserView(generics.CreateAPIView): """Create a new user in the system.""" serializer_class = UserSerializer authentication_classes = [TokenAuthentication] permission_classes = [permissions.UpdateOwnProfile] filter_backends = (filters.SearchFilter,) search_fields = ('name', 'email',) class UserViewSet(viewsets.ModelViewSet): """List all users.""" queryset = User.objects.all() serializer_class = UserSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] class CreateTokenView(ObtainAuthToken): """Create a new auth token for user.""" serializer_class = AuthTokenSerializer renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES class UserLoginApiView(ObtainAuthToken): """Handle creating user authentication tokens.""" renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES class LogoutView(APIView): """Logout the authenticated user.""" authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): request.user.auth_token.delete() return Response(status=status.HTTP_200_OK) class ManageUserView(generics.RetrieveUpdateAPIView): """Manage the authenticated user.""" serializer_class = UserSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get_object(self): """Retrieve and return the authenticated user.""" return self.request.user -
Django distinct and group_by query using the ORM and MySQL
I'd like to obtain a QuerySet containing all the latest comments for each post using Django ORM. The comments can be ordered ordered by the when field. Suppose the following example: class Post(models.Model): name = models.TextField() class Comment(models.Model): title = models.TextField() when = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Post, on_delete=models.CASCADE) This in raw SQL could be achieved, so I assume Django may have its own way too. I'd like to avoid using raw queries (discouraged by Django documentation). I cannot use distinct() with fields names as I am using MySQL. Any indication is appreciated. -
How can anonymous users interact with Vue3 frontend, using GraphQL and Django backend?
While building a blog app, I want to create a user interaction such as like, dislike and share. However, I want the users to be anonymous (not authenticated). How can I achieve this to display counts for like, dislike and share in Vue 3 JS? I want to fetch the interactions from the backend, as the app mounts (onMounted) lifescycle hook. But when I refresh the page it displays the initial values like(0), dislike (0) and share(0). SocialMediaButtons.vue: <template> <div> <button @click="likePost" :disabled="isLiked"> <font-awesome-icon icon="thumbs-up" style="color: green; font-size: 24px; margin-right: 50px;" /> Like ({{ interactions.like }}) </button> <button @click="dislikePost" :disabled="isDisliked"> <font-awesome-icon icon="thumbs-down" style="color: red; font-size: 24px; margin-right: 50px;" /> Dislike ({{ interactions.dislike }}) </button> <button @click="sharePost" :disabled="isShared"> <font-awesome-icon icon="fa-solid fa-share" style="color: #0077B5; font-size: 24px; margin-right: 50px;" /> Share ({{ interactions.share }}) </button> <div class="social-media-icons" style="display: flex; justify-content: center; align-items: center; height: 10vh;"> Share this post on: <button @click="shareOnFacebook"> <font-awesome-icon :icon="facebookIcon" class="fa-2x icon-facebook" style="margin-right: 50px;" /> </button> <button @click="shareOnLinkedIn"> <font-awesome-icon :icon="['fab', 'linkedin']" class="fa-2x icon-linkedin" style="margin-right: 50px;" /> </button> </div> </div> </template> <script setup> import { ref, computed, watch, onMounted } from 'vue'; import { useRoute } from 'vue-router'; import { useQuery } from '@vue/apollo-composable'; import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'; import … -
How to implement a mobile_no to be passed inorder to access tokens and not the default username and password
I'm not using password, by default simplejwt requires a default user so it prompts me for username, password and mobile_no - but I only want to user mobile no. I tried to override the TokenObtainpairSerializer - but to no success