Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Load jquery function in vue from an external file
I am working django integrated with vuejs via webpack loader. In django's "base.html" file all static files are loaded and there is the point where vue is rendered. In vue I have a page where there is a table where all the data is loaded. In the simple html template the table and the people were via the js file that used jquery. With vuejs I can't load it. In base.html: <body class="vertical-layout vertical-menu-modern navbar-floating footer-static " data-open="click" data-menu="vertical-menu-modern" data-col=""> <div id="app"> </div> {% render_bundle 'app' %} <script src="{% static 'dashboard/js/scripts/pages/app-user-list.js' %}"></script> </body> In app-user-list.js: $(function () { ('use strict'); var dtUserTable = $('.user-list-table'), newUserSidebar = $('.new-user-modal'), newUserForm = $('.add-new-user'), select = $('.select2'), dtContact = $('.dt-contact'), statusObj = { 1: { title: 'Pending', class: 'badge-light-warning' }, 2: { title: 'Active', class: 'badge-light-success' }, 3: { title: 'Inactive', class: 'badge-light-secondary' } }; // Users List datatable if (dtUserTable.length) { dtUserTable.DataTable({ ajax: "http://127.0.0.1:8000/static/dashboard/data/user-list.json", // JSON file to add data columns: [ other... The path in the code where ajax requests leads to a file with a list of users. In this way I have loading problems because the file is loaded once if I go through vue on the page where the … -
Using different languages(frameworks) in the same web project [closed]
Please is there a way to work on a project with different languages and their frameworks. For example, I have a to build an e-commerce website with a team of three backend developers One node.js, one django and one laravel The node.js developer is to work on the products section The django developer is to work on user registration and authentication While the laravel developer is to work on the payments system Is there a way the various parts can be linked to work together on the same project? -
Create multiple website templates with django cms or any tool
Can Django be used to create a website for creating custom websites depending on the user needs? There will be more than one template and each user will have a custom url for their websites. I don't know if this can this be achieved with Django CMS. -
Django migration: got relation does not exist or relation already exists errors
I tried to port a Diango app from one server to another and change database engine from sqllite3 to postgres. After I pulled the app from github to the new server and reconfigured database settings for postgres, I got a relation not existing error when I tried to migrate as shown below. $ python manage.py migrate Traceback (most recent call last): File "/data/apps/anaconda3/envs/parts_env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "parts" does not exist LINE 1: SELECT "parts"."type" FROM "parts" ... But after I created the table in the database and tried again, I got a relation already exists error as shown below. $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, partsdb, sessions Running migrations: Applying partsdb.0001_initial...Traceback (most recent call last): File "/data/apps/anaconda3/envs/parts_env/lib/python3.8/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "parts" already exists ... So I'd get the "relation does not exist" error if I dropped the table and I'd get the "relation already exists" error if I created the table. I omitted the tracing outputs which are from Django libraries and very lengthy, but I can supply them if they may help. Thanks. -
Django message + nginx: message showing after 3 times reload !! admin login redirects back to admin login page after giving right credentials
I have built a Django application. It was working fine in the development mode. But I tried to host it in the digital ocean, Every thing worked fine, but when any error message is sent as a response, It doesn't show instantly in the front-end. Weirdly enough, If I reload three times, the error message becomes visible. my nginx configuration: listen 80; server_name <domain name>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/saadman/<project name>/staticfiles/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } my gunicorn service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=saadman Group=www-data WorkingDirectory=/home/saadman/<projectname> ExecStart=/home/saadman/<projectname>/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ <projectname>.wsgi:application [Install] WantedBy=multi-user.target -
Django Rest Framework - drf-spectacular add extra models to schemas
I used drf-spectacular and have two questions about this module. I wanna create custom Schemas and overwrite Schema in API endpoints. How to do this? I search a way to add custom models to Schemas but without connected this with endpoints. I see that i can add custom Schema by: """ inline_serializer( name='PasscodeResponse', fields={ 'passcode': serializers.CharField(), } ), But don't know where to put this. I wanna just see this in this Schemas like on screen: -
How to change backgrounf color of my HTML/CSS template?
I'm using this simple Boostrap template for a work and I just can't change the background color. I tried to change the background-color value over t my css file, and that has no effect at all. Tried to put the entire index file inside a div with a background-color tag, but my website is still white. Please help. -
Error in Django Model and Serializer - (1048, "Column 'dso_id' cannot be null")
I am trying to create a user profile, I feel i have everything correct but still it doesn't register. You see my codebase below, please help What i did: Models.py: class UserManager(BaseUserManager): def create_user(self, username, email, name, address,roleId,customerId,dso password=None,): if username is None: raise TypeError('User should have a userame') if email is None: raise TypeError('Users should have a Email') user = self.model(username=username , email = self.normalize_email(email)) user.set_password(password) user.save() return user def create_superuser(self, username, email, password=None): if password is None: raise TypeError('User should have a password') user=self.create_user(username,email,password,) user.is_superuser = True user.is_staff = True user.save() return user class User(models.Model): dso = models.ForeignKey(Dso,related_name='dso',default=NULL,blank=False,on_delete=models.CASCADE) name = models.CharField(max_length=70, blank=False, default='') email = models.EmailField(max_length=70, blank=False, default='') password = models.CharField(max_length=70, blank=False, default='') address = models.CharField(max_length=70, blank=False, default='') roleId = models.IntegerField(blank=False, default='1') isActive = models.BooleanField(blank=False, default=True) customerId = models.CharField(max_length=70, blank=False, default='') dateJoined = models.DateTimeField(auto_now_add=False, blank=False, default=NULL) @property def energy_data(self): energydata = EnergyData.objects.filter(customerId=self.customerId).first() return energydata Serializers.py: class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length = 68, min_length=6, write_only = True) class Meta: model=User fields=['email','username','password','name','address','customerId', 'dso', 'roleId'] def validate(self, attrs): email = attrs.get('email', '') username = attrs.get('username', '') if not len(username) >= 4: raise serializers.ValidationError('Username must be morethan 4 letters or characters') return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) Views.py: class RegisterView(generics.GenericAPIView): serializer_class= … -
Is there a way to capture permission change in Django Guardian?
I would like to receive a signal after permission is changed on the object level. Django Guardian allows us to set object-level permissions. Based on the permission change, I'd like to perform some actions. How to receive a signal on object level permission change? -
Accessing custom directory under static directory in Django
I am learning Django. I know how to add use {% static "abc/xyz" %} in templates. But now I want to use something similar in views.py file. For example project->my_app->static->resources->abc.json is the file I need to access in the views.py of my_app. When I tried f = open('resources/abc.json') it didn't work. How do I do it correctly? -
Django most efficient way to count users and types
In my django project I have a user model and I want to count the different status of users. I am not sure the best way to approach as thats the top most level model so i dont think I can use annotate. I tried it but of course i on workers = get_user_model().objects.annotate( not_active_workers=Count("id", filter=Q(is_active=False, status=0)) ).annotate( active_not_complete_workers=Count("id", filter=Q(is_active=True, profile_completed=False, status=0)) ).annotate( complete_applicant_workers=Count("id", filter=Q(is_active=True, profile_completed=True, status=0)) ).annotate( former_workers=Count("id", filter=Q(is_active=False, status=2)) ).annotate( accepted_workers=Count("id", filter=Q(is_active=False, status=1)) ).filter(role=2) dict( not_active=workers[0].not_active_workers, active_not_complete=workers[0].active_not_complete_workers, complete_applicant=workers[0].complete_applicant_workers, former=workers[0].former_workers, accepted=workers[0].accepted_workers, ) The other way is count() for each filter, but it would be several queries. I think these would be pretty fast but maybe Im missing an easier way to count all queries as a dataset in 1 hit? -
authenticating normal users in django
enter image description here i am having issues with django built in forms.py which is in contrib.auth-- forms.py, i am having lot of errors in forms.py, for development i am using vscode i dont know it is isssue with vscode or what!, i am also unable to authenticate normal users after signup bcz of these errors maybe, vscode shows 162 errors in terminal, i also tried to download django from github, also reinstalled django, i dont know where is problem, i have attched screenshot. -
How do I reach a containerized django web app running in visual studio code debug mode?
After some path changes due to being a git submodule, I was able to configure a launch.json and tasks.json to get my application running in debug mode. Here are the tasks.json { "version": "2.0.0", "tasks": [ { "type": "docker-build", "label": "docker-build", "platform": "python", "dockerBuild": { "tag": "signmeasures:latest", "dockerfile": "${workspaceFolder}/signmeasures-frontend/Dockerfile", "context": "${workspaceFolder}", "pull": true } }, { "type": "docker-run", "label": "docker-run: debug", "dependsOn": [ "docker-build" ], "python": { "args": [ "runserver", "0.0.0.0:8000", "--nothreading", "--noreload" ], "file": "signmeasures-frontend/signmeasures/manage.py" } } ] } and here is the launch.json { "configurations": [ { "name": "Docker: Python - Django", "type": "docker", "request": "launch", "preLaunchTask": "docker-run: debug", "python": { "pathMappings": [ { "localRoot": "${workspaceFolder}/signmeasures-frontend", "remoteRoot": "/app" } ], "projectType": "django", "port": 5678, "host": "localhost" }, } ] } I'm not too familiar with setting up the debug container or docker in general, I'm still trying to learn. When I hit the debug button on the debug tab, it builds a container and then in the debug console I see this but when I try to go to localhost:8000 it does not load the web app. It shows this: I'm not sure what I need to change to be able to reach it and set breakpoints to … -
Should I override clean or validate_unique? What's the difference?
What is the difference if in models.py I had: def validate_unique(self, exclude=None): qs = KeyDefinition.objects.filter(key_name=self.key_name, developer_email=self.developer_email) print(qs) if qs: raise ValidationError ( {'key_name' : ['This Key Name already exists']} ) return super().validate_unique(exclude) vs: def clean(self): qs = KeyDefinition.objects.filter(key_name=self.key_name, developer_email=self.developer_email) print(qs) if qs: raise ValidationError ( {'key_name' : ['This Key Name already exists']} ) These seem to have no difference in the outcome. Basically, I want to make sure that each developer can't submit a key with the same name as one they already have (but two developers can have a key with the same name). I have handled this at the database level by using the unique_together option in the Meta class. -
Rabbitmq fails to boot
Rabbitmq refuses to work on my pc with the error: BOOT FAILED =========== Exception during startup: error:{case_clause,closed} rabbit_networking:record_distribution_listener/0, line 366 rabbit_networking:boot/0, line 80 rabbit:do_run_postlaunch_phase/1, line 958 {"init terminating in do_boot",{error,{case_clause,closed}}} init terminating in do_boot ({error,{case_clause,closed}}) Crash dump is being written to: c:/Users/user/AppData/Roaming/RabbitMQ/log/erl_crash.dump...done I tried downloading the erlang and rabbitmq versions that are used in the tutorial probably the new versions had different configurations or something but i was stuck only with rabbitmq 3.10.6 from the official rabbitmq website. So i tried my best to debug and tried checking the erl_crash.dump file and didn't get much from it other than random logs but got a more useful information when i checked c:/Users/user/AppData/Roaming/RabbitMQ/log/rabbit@DESKTOP-J9C9L63.log the error in the log was: [error] <0.380.0> epmd monitor failed to retrieve our port from epmd: closed But unfortunately couldn't get anything on the error online, I couldn't find the file either. I'm trying to integrate rabbitmq with django-celery,your help will be really much appreciated. -
How to use Content-Security-Policy to disable header " X-Frame-Options: deny "?
I created a website in Django that I deployed on heroku. I am trying to display this website from an html page using an iframe. However, when I load my html page, I get the error: gkwhelps.herokuapp.com refused the connection. And when inspecting the page I get the following message:Refused to display 'http://gkwhelps.herokuapp.com/' in a frame because it set 'X-Frame-Options' to 'deny'. To solve this problem, I modified my settings.py like this: MIDDLEWARE = [ ... 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... from django.http import HttpResponse from django.views.decorators.clickjacking import xframe_options_exempt @xframe_options_exempt def ok_to_load_in_a_frame(request): return HttpResponse("This page is safe to load in a frame on any site.") and I updated my site. But despite this, I still get the same error when I reload my page. I don't know why yet I updated my site. -
Aggregate by another table after annotate
I have next annotate qs.annotate( goods_with_sales=Count('goods', filter=Q(goods__history__sales__gt=0)), ) Same goods_with_sales_percent=goods_with_sales / sum_sales * 100 I need get percent of goods_with_sales to sum of all goods__history__sales. I try it with Window but not happiness... This is raw sql query: SELECT "wb_brand"."created", "wb_brand"."modified", "wb_brand"."id", "wb_brand"."name", COUNT("wb_good"."id") FILTER ( WHERE "wb_stockshistory"."sales" > 0 ) AS "goods_with_sales" FROM "wb_brand" LEFT OUTER JOIN "wb_good" ON ( "wb_brand"."id" = "wb_good"."brand_id" ) LEFT OUTER JOIN "wb_stockshistory" ON ( "wb_good"."id" = "wb_stockshistory"."good_id" ) GROUP BY "wb_brand"."id" Also I tried this with CTE, but not happiness also. How can I solve it with Django ORM (prefer) or with SQL ? P.S. Also must be CASE/WHEN condition for divisizon by zero if sum_sales == 0. -
HTMX not working when using paginate with infinite-scroll
I have a product card in my Django Application, when clicked, adds to cart. I'm using infinite-scroll and django-pagination. The issue is with the pagination, however. The first page of results works wonderfully with HTMX. However, the second page and all pages beyond does not work on click. Upon inspecting the page, the html does appear to be rendered properly and I can see the hx-get call with the proper url. But upon clicking, nothing happens. Maybe I'm missing something obvious here, but any help would be appreciated! HTML <div class="container" data-infinite-scroll='{ "path": ".pagination__next", "append": ".product-card", "history":"false"}'> {% block content %} {% include 'includes/cards.html' %} {% include 'includes/sidebar.html' %} {% endblock content %} </div> <ul class="pagination mt-50 mb-70"> {% if products.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ products.previous_page_number }}"><i class="fa fa-angle-left"></i></a></li> {% endif %} <li class="page-item"><a class="page-link" href="#">{{ products.number }}</a></li> {% if products.has_next %} <li class="page-item"><a class="pagination__next" href="?page={{ products.next_page_number }}"><i class="fa fa-angle-right"></i></a></li> {% endif %} </ul> views.py def shop(request): anabanner = AnaBanner.objects.all() gender = Gender.objects.all() categories = Category.objects.all() colors = Color.objects.all() materials = Material.objects.all() query = request.GET.get('query','') products = Product.objects.all().order_by('-pk') if query: products = products.filter( Q(name__icontains=query)| Q(sub_name__icontains=query) ).distinct() paginator = Paginator(products, 8) page = request.GET.get('page') products = paginator.get_page(page) context = {'products':products,'categories':categories,'gender':gender,'anabanner':anabanner,'colors':colors,'materials':materials} … -
I am trying to run "python manage.py runserver" for Django project
1 This is the error I got I tried changing the SQLite version Still it does not work -
Handling repetitive content within django apps
I am currently building a tool in Django for managing the design information within an engineering department. The idea is to have a common catalogue of items accessible to all projects. However, the projects would be restricted based on user groups. For each project, you can import items from the catalogue and change them within the project. There is a requirement that each project must be linked to a different database. I am not entirely sure how to approach this problem. From what I read, the solution I came up with is to have multiple django apps. One represents the common catalogue of items (linked to its own database) and then an app for each project(which can write and read from its own database but it can additionally read also from the common items catalogue database). In this way, I can restrict what user can access what database/project. However, the problem with this solution is that it is not DRY. All projects look the same: same models, same forms, same templates. They are just linked to different database and I do not know how to do this in a smart way (without copy-pasting entire files cause I think managing this … -
What does "DEFAULT_PERMISSION_CLASSES will only work for the views or objects that don't have permissions explicitly set." mean?
I was reading below mentioned blog which is about Built-in permissions in DRF Source: https://testdriven.io/blog/built-in-permission-classes-drf/ In this blog there is statement: DEFAULT_PERMISSION_CLASSES will only work for the views or objects that don't have permissions explicitly set. You don't necessarily need to use built-in classes here. You can use your own custom classes as well. Question: What does set permissions explicitly means? -
How to pass data from request body in unit test django
I have modified get_queryset() method that looks like this: def get_queryset(self): type_of_review = self.request.data['type_of_review'] queryset = Reviews.objects.filter(type_of_review=type_of_review).order_by('-id')[:3] return queryset It sorts my models according to the type_of_review field, orders them and retrieves 3 last. When I was trying to write a unit test to it, I ran into a problem that I cannot find a reliable or working way to pass filter argument into my get_queryset() method. I tried doing it like this: def test_list_three_review(self): self.data = [ReviewsFactory.create() for i in range(10)] response = self.client.get(self.url2, type_of_review='Team') self.assertEqual(response.status_code, status.HTTP_200_OK) But got an error: test_list_three_review - KeyError: 'type_of_review' Can somebody explain to me what am I doing wrong? Will gladly provide any additional information. Thanks anyway! -
How to easily transform a series of formatted text to SQL?
I am building a simple Question-Answer system about checking attendance of students with Django. I hope that when I input a question like 'Did student xxx attend the course in xxx Date',it can query the database and return the correct answer. How can I transform the input into SQL easily without using complex AI technology? Thanks very much. Here's part of my database: enter image description here -
Static files not loading using nginx and docker
I'm having approximately the same error as in this question, as concerning Django, all my pages are loaded correctly but not my static files. I guess it has something to do with an error in my configuration files, however even though I've been searching for quite some time, I couldn't find anything to solve my problem. Here is my Django Dockerfile : FROM python:3.10.5-alpine RUN pip install --upgrade pip RUN wget https://upload.wikimedia.org/wikipedia/commons/b/b9/First-google-logo.gif -O media/media.gif COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./src /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] nginx.conf upstream django { server django_gunicorn:8000; } server { listen 80; server_name 127.0.0.1; location / { proxy_pass http://django; } location /static/ { alias /static/; } location /media/ { alias /media/; } } nginx Dockerfile FROM nginx:1.19.0-alpine COPY ./nginx.conf /etc/nginx/conf.d/nginx.conf docker-compose.yml version: '3.7' services: django_gunicorn: volumes: - static:/static - media:/media env_file: - env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static - media:/media ports: - "80:80" depends_on: - django_gunicorn volumes: static: media: And I get errors like that : testapp-django_gunicorn-1 | testapp-django_gunicorn-1 | 9771 static files copied to '/app/static'. testapp-django_gunicorn-1 | [2022-07-21 12:27:36 +0000] [9] [INFO] Starting gunicorn 20.1.0 testapp-django_gunicorn-1 | [2022-07-21 12:27:36 +0000] … -
How to run background task with Django?
I'm looking to run heavy tasks (more than 5 minutes) in the background with django. When a heavy task is launched, django stops responding and it becomes impossible for users to navigate between pages until the task is finished. For me a solution would be to run these heavy tasks in the background or in parallel in order to allow the user to be able to navigate between the pages in the meantime. Do you know how I can do this ?