Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PostgreSQL JOIN query much slower via Django than on simple Python interpretor
here is a topic I have been struggling on for a small while now. For now, I decided to just limit the requests sizes, but I'd like to know why this happened. If you can take some time solving this problem, thank you. Context Here are the models: class Zone(Model): zone_id = BigAutoField(primary_key=True) type = CharField(max_length=6, choices=('TypeA', 'TYpeB', 'TypeC')) other_fields class User(Model): user_id = BigAutoField(primary_key=True) other_fields class Access(Model): access_id= BigAutoField(primary_key=True) zone_id = BigIntegerField(null=False, empty=False) user_id = BigIntegerField(null=False, empty=False) There are two databases. These models are on the one I do not own, I only have USAGE rights. That is why I did not add ForeignKeyField, fearing that Django would want to consider its own automatically generated indexes with this, while that's not how the database has been set. The database is using PostgreSQL. The table Zone has its indexes zone_access_id_idx and zone_user_id_idx set already, and that is why, I suppose, when I run the predictable JOIN sql query (detailed below) on psql console and even on simple python, independent script using psycop2, the result is instantaneous. (the size of zone table is like 100,000 in total, but I filter it to 100 in the query) (the nb of accesses I … -
Django: Passing argument via image to get a filtered view in next page
I am having a big confusion right now and can't any good answers online about my issue. What I am trying to do is, to let the users click on an image. I have 52 different images on my page and by clicking on the image i want to pass an int between 1-53 (52 is missing) in order to get a filtered view. What I have is models.py class CentroidCount(models.Model): id_centroid_count = models.AutoField(primary_key=True) id_observation = models.ForeignKey('Observation', models.DO_NOTHING, db_column='id_observation', blank=True, null=True) step = models.SmallIntegerField(blank=True, null=True) centroid = models.SmallIntegerField(blank=True, null=True) count = models.SmallIntegerField(blank=True, null=True) class Meta: managed = False db_table = 'centroid_count' ordering = ['id_observation', 'step', 'centroid'] def get_absolute_url(self): return reverse('centroid-detail', args=[str(self.id_centroid_count)]) def __str__(self): return 'Observation: %s' % (self.id_observation) urls.py urlpatterns = [ path('', views.index, name='index'), path('observations/', views.ObservationListView.as_view(), name='observations'), ] views.py class ObservationListView(generic.ListView): model = CentroidCount context_object_name = 'observation_list' queryset = CentroidCount.objects.filter(centroid__in=[]).order_by('id_observation').values_list('id_observation', flat=True).distinct() template_name = 'centroid_webapp/observation_list.html' def get_queryset(self): return CentroidCount.objects.filter(centroid__in=[2]).order_by('id_observation').values_list('id_observation', flat=True).distinct() and the image part of the html <div class="col-sm"> <img src="{% static 'images/1.png'%}" class='img-fluid' alt='Responsive image'> </div> What i still don't understand fully is how can be this done dynmaically. What i do have now is a static page that is filterint out all "id_observations" with the number 2. But … -
Django not serving static files and not stylizing anything
I downloaded a template in the form of a zip file on my machine. It has a file for a homepage, auth-login.html. If I load this on its own then it loads correctly, I see styling and I don't get any console errors. But it seems like I can't get this template to load its css and styling in my Django project via python manage.py runserver with DEBUG=true. I'm trying to just get this on a development server and I haven't really been able to get past step 1. When I try to go to my application's home page, I see unstylized times new roman text in my browser. No styling loads on the page at all. I'm not getting server/console errors either. My Django project is of the following structure lpbsproject/ project_root/ staticFiles/ (STATIC_ROOT, where collectstatic copies to) project_app/ settings.py urls.py wsgi.py, asgi.py, __init__.py... static/ (STATIC_URL, original location of static files) assets/ (this folder is copied/pasted from the template .zip) css/, js/, ... user_auth/ migrations views.py admin.py, models.py, apps.py, test.py ... templates/ manage.py Here's the <head> of my html file with all the <link> and <script> statements. These currently aren't generating errors. {% load static %} <!doctype html> <html … -
django.core.exceptions.ImproperlyConfigured: Cannot import 'educations'. Check that 'careers.apps.EducationsConfig.name' is correct
I can't import my apps. I think path is ok but don't know how to solve this problem. is there any problem in my code? carrers>apps.py from django.apps import AppConfig class CareersConfig(AppConfig): name = "careers" class EducationsConfig(AppConfig): name = "educations" django.core.exceptions.ImproperlyConfigured: Cannot import 'educations'. Check that 'careers.apps.EducationsConfig.name' is correct. settings.py > PROJECT_APPS = [ "cores.apps.CoresConfig", "users.apps.UsersConfig", "reviewers.apps.ReviewersConfig", "careers.apps.CareersConfig", "careers.apps.EducationsConfig", "conversations.apps.ConversationsConfig", "unions.apps.UnionsConfig", "posts.apps.PostsConfig", -
Default Language problem in django although Language_code is set
Default Language problem in django although Language_code is set.The problem is as follows: LANGUAGES = ( ('kmr', gettext_noop('Kurmanji')), ('ckb', gettext_noop('Sorani')), #('en', gettext_noop('English US')), ) LANGUAGE_CODE = 'kmr' if 'en' is in commented then default language works as required.But if I un-comment the 'en'then 'en' remains the default language in django app.whatever i tried it is always makes 'en' as default langues. -
Elastic Beanstalk Editing Files Online?
I deployed my Django website on AWS elastic beanstalk. I have deployed PHP websites previously on GoDaddy and some other hosting. As there is method to edit your PHP files over internet as I can login my account on another pc and edit the files. But until now I am unable to find a way to do so in elastic beanstalk to let me or some one else to edit the files online. Currently all my are on my laptop. It may be silly question but I just want to know. -
Django OSError [Errno 101]
when i test my project on my local machine it was work butt when i deploy my code on my host after submit form data i get this error and i don't receive email. settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'vanguardteam99@gmail.com' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = "*********" views.py: send_mail( 'همکاری با ما', 'name: {}\n, age: {}\n, cell_phone: {}\n, email: {}\n, skills: {}\n, message: {}\n'.format( name, age, cell_phone, email, dev_skills_str, description), settings.EMAIL_HOST_USER, ['vangaurdteam99@gmail.com'] ) error massage: OSError at /vanguard_projects/project_request [Errno 101] Network is unreachable Request Method: POST Request URL: http://vanguard-group.ir/vanguard_projects/project_request Django Version: 3.1.3 Exception Type: OSError Exception Value: [Errno 101] Network is unreachable Exception Location: /opt/alt/python37/lib64/python3.7/socket.py, line 716, in create_connection Python Executable: /home/vanguard/virtualenv/vanguard_land/3.7/bin/python3.7_bin Python Version: 3.7.8 Python Path: ['/home/vanguard/vanguard_land', '/opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts', '/home/vanguard/virtualenv/vanguard_land/3.7/lib64/python37.zip', '/home/vanguard/virtualenv/vanguard_land/3.7/lib64/python3.7', '/home/vanguard/virtualenv/vanguard_land/3.7/lib64/python3.7/lib-dynload', '/opt/alt/python37/lib64/python3.7', '/opt/alt/python37/lib/python3.7', '/home/vanguard/virtualenv/vanguard_land/3.7/lib/python3.7/site-packages'] Server time: Tue, 24 Nov 2020 13:27:01 +0000 -
What's the best way to create a web mapping app with Django?
Should I use leaflet, vue-leaflet, folium, mapbox or other techno ? Thank you -
Django reverse foreignkey filter return multiple same objects
I have a favorite system. So I check that a user already liked the post. I've written this query. But there is a problem since I don't delete the favorite's records. I just change the status of favorite's record. So if the user deletes the favorite before, my queryset return 2 rows for each them. I use MySQL for the database. def is_favorite(self, user): if user.is_authenticated: return self.annotate(is_favorite=Case( When(Q(favorites__user=user, favorites__is_deleted=False), then=Value(True)), default=Value(False), output_field=BooleanField() ) ).prefetch_related("favorites") return self.annotate(is_favorite=Value(False, output_field=BooleanField())) My query Blog.objects.all().is_favorite(self.request.user).distinct() Queryset's return [ { "id" : 1, "title": "foo", "is_favorite" : false }, { "id" : 1, "title": "foo", "is_favorite" : true } ] -
I already have implementation of python-docx to download docx file in my django project, now i want to convert it into pdf
I already have an implementation of python-docx to download docx file in my django project, now i want to download pdf with same content and same format -
ModuleNotFoundError: No module named 'django' by Deploying on Azure
I'm trying to deploy a django web app to the Microsoft Azure and this is correctly deployed by the pipeline on DevOps Azure, but I get the error message (ModuleNotFoundError: No module named 'django) on portal Azure and cannot reach my app via the URL. The app also works properly locally Here is the whole error message: '''https://pastebin.com/mGHSS8kQ''' How can I solve this error? -
pylint_django raises import-errors when not specifying --init--hook option
my_project __init__.py app __init__.py settings.py manage.py core __init__.py common.py students __init__.py models.py views.py serializer.py teachers __init__.py models.py views.py serializer.py When I run pylint --load-plugins pylint_django students, I got these errors: E0611: No name 'common' in module 'core' (no-name-in-module) E0401: Unable to import 'teachers.serializer' (import-error) E0401: Unable to import 'teachers.models' (import-error) My students/serilizer.py: from rest_framework import serializers from students.models import Student from teachers.serializer import TeacherSerializer from teachers.models import Teacher from core.common import method class StudentSerializer(serializers.ModelSerializer): pass I don't get theses error when I import the models of the same app ! I don't get any error when I specify --init--hook option: pylint --load-plugins --init--hook "__import__('sys').path.insert(0, '.'); __import__('django').setup();" pylint_django students How can we overcome these errors without specifying the --init-hook?? -
Django ORM Query: How to get record that Not Exist in other table
How to achieve this Raw SQL query in Django ORM?: dbfiddle. So I have 2 table, Table user and payment, i need to get the user_id that not have a record in payment table (see expected result): User table: Payment table: Result Expected -
Cannot install psycopg2, django-heroku, grpcio on MacOS Catalina 10.15.7
I am trying to install requirements on a Django project but I get this error. I've tried almost everything I saw but still no luck. I have tried pip install -r requirements.txt, pip install psycopg2, pip install psycopg2-binary but none of them worked. My Python version is 3.9.0 and I've also tried it with 3.8.2 but still got the same error. Here is the stack trace: ... 1 warning generated. gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DPSYCOPG_VERSION=2.8.6 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=130001 -DHAVE_LO64=1 -I/Users/burakakyalcin/Projects/hakko_api/venv/include -I/Library/Frameworks/Python.framework/Versions/3.9/include/python3.9 -I. -I/usr/local/include -I/usr/local/include/postgresql/server -c psycopg/xid_type.c -o build/temp.macosx-10.9-x86_64-3.9/psycopg/xid_type.o gcc -bundle -undefined dynamic_lookup -arch x86_64 -g build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_asis.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_binary.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_datetime.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_list.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_pboolean.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_pdecimal.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_pfloat.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_pint.o build/temp.macosx-10.9-x86_64-3.9/psycopg/adapter_qstring.o build/temp.macosx-10.9-x86_64-3.9/psycopg/aix_support.o build/temp.macosx-10.9-x86_64-3.9/psycopg/bytes_format.o build/temp.macosx-10.9-x86_64-3.9/psycopg/column_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/connection_int.o build/temp.macosx-10.9-x86_64-3.9/psycopg/connection_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/conninfo_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/cursor_int.o build/temp.macosx-10.9-x86_64-3.9/psycopg/cursor_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/diagnostics_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/error_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/green.o build/temp.macosx-10.9-x86_64-3.9/psycopg/libpq_support.o build/temp.macosx-10.9-x86_64-3.9/psycopg/lobject_int.o build/temp.macosx-10.9-x86_64-3.9/psycopg/lobject_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/microprotocols.o build/temp.macosx-10.9-x86_64-3.9/psycopg/microprotocols_proto.o build/temp.macosx-10.9-x86_64-3.9/psycopg/notify_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/pqpath.o build/temp.macosx-10.9-x86_64-3.9/psycopg/psycopgmodule.o build/temp.macosx-10.9-x86_64-3.9/psycopg/replication_connection_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/replication_cursor_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/replication_message_type.o build/temp.macosx-10.9-x86_64-3.9/psycopg/solaris_support.o build/temp.macosx-10.9-x86_64-3.9/psycopg/typecast.o build/temp.macosx-10.9-x86_64-3.9/psycopg/utils.o build/temp.macosx-10.9-x86_64-3.9/psycopg/win32_support.o build/temp.macosx-10.9-x86_64-3.9/psycopg/xid_type.o -L/usr/local/lib -lpq -lssl -lcrypto -o build/lib.macosx-10.9-x86_64-3.9/psycopg2/_psycopg.cpython-39-darwin.so ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command '/usr/bin/gcc' failed with exit code 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /Users/burakakyalcin/Projects/hakko_api/venv/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/lx/1m5zgk591xj0_fyybjhw1wm00000gn/T/pip-install-tiftlw89/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/lx/1m5zgk591xj0_fyybjhw1wm00000gn/T/pip-install-tiftlw89/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', … -
media Image url not opening in django template
Image from media not opening in template in my django app. below is urls or my project from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('myroyalkennel', include('myroyalkennel.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Below is my settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' below is my views.py* def store (request): items = products.objects.all return render(request, "myroyalkennel/store.html", {"itms":items}) below is my template: <body> <table> <tr> <th>image</th> <th>SERIAL NUMBER</th> <th>SERIAL NUMBER</th> <th>PRODUCT NAME</th> <th>VARIENT</th> <th>MRP</th> <th>DISCOUNTED PRICE</th> <th>DISCOUNT PERCENT</th> <th>IN STOCK</th> </tr> {%if itms %} {% for item in itms %} <tr> <td>{{item.image.url}}</td> <td>{{item.Serial_number}}</td> <td>{{item.product_name}}</td> <td>{{item.Varient}}</td> <td>{{item.MRP}}</td> <td>{{item.Discounted_price}}</td> <td>{{item.Discount_percent}}</td> <td>{{item.In_Stock}}</td> </tr> {% endfor %} {% endif %} </table> </body> below is my model * class products(models.Model): Serial_number = models.CharField(max_length=10) product_name = models.TextField() Varient = models.CharField(max_length=15) MRP = models.IntegerField() Discounted_price = models.IntegerField() Discount_percent = models.CharField(max_length=6) In_Stock = models.CharField(max_length=15) image = models.ImageField(upload_to="asset/image",default="") def __str__(self): return self.product_name When I am calling the image in template with {{ item.image.url}} it gives path /media/asset/image/rkci_logo.jpg but image does not open. -
Use Wordpress for authenticating Django users
I have a WordPress site with multiple users configured. I also have a Django-based site. I would like to have my Django site use the Wordpress site to authenticate users. Is it possible to have Wordpress serve as an authentication server for a Django site? If so, how? Thanks! -
I want to show customer coin but its only shwoing customer id
i am trying to show account balance system in my project.Like a customer has 1000$ when that customer log inhe will be shown his balance is 1000$.But whenever I try to fetch this data it only shows its id, but I want to show his amount not his id.How can I do this ??I am really confused about this part and got stuck here Here is my Customer Model: class Customer(models.Model): phone_number = models.CharField(max_length=100, default=1) email = models.EmailField( default=1) password = models.CharField(max_length=100) coin = models.FloatField(null=True, blank=True) How can I only show his amount when he is logged in ?? Please help me asap -
Reverse migration id column primary key
I have a table that had an id uuid primary key column. And i want to change this column into Char primary key column. So i did a migration that removes the field and then re-add. When i migrate everything migrates successful. But if i reverse the migration i get django.db.utils.IntegrityError: column "id" contains null values when tries to execute the following sql ALTER TABLE "Test" ADD COLUMN "id" uuid NOT NULL PRIMARY KEY. Below is my migration operations: operations = [ migrations.RemoveField( model_name='employee', name='id', ), migrations.AddField( model_name='employee', name='id', field=models.CharField(default='abcd', max_length=100, primary_key=True, serialize=False), preserve_default=False, ), ] -
coverage showing 100% for settings.py file
I'm confused with coverage report which is generated with help of pytest. Here is my coverage html report. settings.py file is showing 100% covered, not sure how it is.. ? Also, the following Loginform also shown as covered so I have added another dummy form even it is showing covered. I'm facing difficulty in understanding this, though I don't have any tests added for settings or for the above forms it's showing as 100% covered, with this I'm not confident whether my code is properly tested or not. -
Django Query how to display a count of records with a distinct dates and display date and count
I'm trying to create a Django query that as output will give me a list of dates and the count of records against those dates. This is my current query which gives me a count of distinct dates as {'dates':2} stats = models.SearchResultStat.objects.values().filter(organisation=organisation.id).annotate(date=TruncDate('created')) \ .values('date') \ .distinct() \ .aggregate(dates=Count('date')) But what I need is [{'2020-11-01' : 2},{'2020-11-02' : 1}] How do I achieve this? -
Forbidden (403) - CSRF verification failed. Request aborted in django when load in Iframe
Django CSRF error in Iframe. When I'm trying to log in its raises the error. Otherwise, it's work fine Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. I'm used LoginView for login also declared {% csrf_token %} in template form. -
Incomplete response format while displaying large number of users in get request?
This is my api view class UserListViewSet(ListModelMixin,GenericViewSet): serializer_class = UserListSerializer permission_classes = [IsAuthenticated] # pagination_class = BasicPagination authentication_classes = [TokenAuthentication, ] queryset = User.objects.filter(is_approved=True) I have the huge number of users more than 7000 users. This api used to give all the users in correct format when users were around in 3-4000 but when the users list get around 6000 then the response is displaying like this. [ { "first_name": "first name", "middle_name": null, "last_name":"last name" # user list ends in this format When I test locally if the users are few then there is no problem in response. I am testing the api in postman. Why is this happening ? How can solve this ? -
JavaScript doesn't change in the Browser
I am working on project with Django, when i edit a JavaScript script the Browser does not show changes. It keeps the old version -
how to save html dropdown value to database (django)
i have a form like this: <form action="/processing/save/" method="POST"> <table class="content-table"> <thead> <tr> <th class="tweet">Tweets</th> <th class="type">Tipe Data</th> <th class="manual">Sentimen Manual</th> <th class="auto">Sentimen Otomatis</th> </thead> <tbody> {% for tr in db_training %} <tr> <td class="tweet">{{tr.tweets}}</td> <td class="type">{{tr.dtype}}</td> <td class="manual"> {{tr.manual}} &nbsp; <select id="dstrain_{{ forloop.counter }}" onchange="gettrain(this)"> <option selected disabled="true">Pilih</option> <option value="negatif">Negatif</option> <option value="netral">Netral</option> <option value="positif">Positif</option> </select> </td> <td class="auto">{{tr.auto}}</td> </tr> {% endfor %} </tbody> </table> {% csrf_token %} <div class="processing"> <input class="btn_save" type="submit" value="SIMPAN"> </form> it looks like this: what i want to do is when i click save, the value from dropdown will be inserted to my database (in column "manual"). heres the database: is it complicated? i just started learning django. -
How can I serialize a nested model m2m field to self with django-rest-framework?
I have a User model that has a m2m relation to itself called friends and I'm trying to serialize it to see and update the pk's of users that are in the relation. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField('Email', max_length=254, unique=True) name = models.CharField('Full Name', max_length=35, unique=True, null=False, blank=False) friends = models.ManyToManyField("User", related_name='user_friends', blank=True) serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): password = serializers.CharField( write_only=True, required=False, help_text='Leave empty if no change needed', style={'input_type': 'password', 'placeholder': 'Password'} ) # for setting the password class Meta: model = User fields = ('pk', 'email', 'name', 'friends', 'password') def create(self, validated_data): validated_data['password'] = make_password(validated_data.get('password')) return super(UserSerializer, self).create(validated_data) When I go to my API I see the following: { "user": { "pk": 1, "email": "user@gmail.com", "name": "User", "friends": [ "http://localhost:8000/user_detailAPI/2/" ], } } but I would like for the serializer to display each friend in a list in a manner like this: { "user": { "pk": 1, "email": "user@gmail.com", "name": "User", "friends": [ 2 ], } } Plus if you could let me know how I would be able to add an object to friends field using POST or PUT request it would be nice because I am new to django-rest-framework and I feel like this is an …