Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Query Paramter is not filtering tag with name that includes ++ or + sign
Currently i am having a weird issue where when i try to search query a tag for example tag = Python, then it show all of the articles related to python, { "id": 1, "headline": "Article 1", "abstract": "Abstract 1", "content": "Content 1", "published": "2022-10-05", "isDraft": true, "isFavourite": [ 2 ], "tags": [ "Python" ], but if i try to query search with k++ or c++ or any word that contains +, then it gives response of empty like this { "count": 0, "next": null, "previous": null, "results": [] } I dont understand why it does not show the result although i have a article that contains k++ in tags this is my tags models: class Tags(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="TAG_ID") tag=models.CharField(max_length=25) def get_id(self): return self.tag + ' belongs to ' + 'id ' + str(self.id) class Meta: verbose_name_plural="Tags" ordering= ("id", "tag") def __str__(self): return f'{self.tag}' this is my articles model where tags is coming as m2m field article model class Article(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="ARTICLE_ID") headline=models.CharField(max_length=250) abstract=models.TextField(max_length=1500, blank=True) content=models.TextField(max_length=2500, blank=True) files=models.ManyToManyField('DocumentModel', related_name='file_documents',related_query_name='select_files', blank=True) published=models.DateField(auto_now_add=True, null=True) tags=models.ManyToManyField('Tags', related_name='tags', blank=True) isDraft=models.BooleanField(blank=True, default=False) isFavourite=models.ManyToManyField(User, related_name="favourite", blank=True) created_by=models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="articles") def get_id(self): return self.headline + ' belongs to ' + 'id ' + … -
Heroku: ModuleNotFoundError :No module named 'six'
I am deploying a Django app on Heroku. The application runs successfully on my local machine, which uses Python 3.6.3.rc1. But it failed to deploy (heroku activity). remote: ModuleNotFoundError: No module named 'six' Actually, It was always successful to build and deploy before August 17 2022. $ git push heroku master remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-18 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> Using Python version specified in Pipfile.lock remote: -----> No change in requirements detected, installing from cache remote: -----> Using cached install of python-3.7.14 remote: -----> Installing pip 22.2.2, setuptools 63.4.3 and wheel 0.37.1 remote: Skipping installation, as Pipfile.lock has not changed since last deploy. remote: -----> Installing SQLite3 remote: -----> Skipping Django collectstatic since the env var DISABLE_COLLECTSTATIC is set. remote: -----> Discovering process types remote: Procfile declares types -> release, web remote: remote: -----> Compressing... remote: Done: 74.2M remote: -----> Launching... remote: ! Release command declared: this new release will not be available until the command succeeds. remote: Released v492 remote: https://license-web-test.herokuapp.com/ deployed to Heroku remote: Verifying deploy... done. remote: Running release command... remote: remote: Traceback (most recent call last): … -
Django Datatable.net with filters, CRUD and pagination
I am trying to build a fully functional datatable with a lot of entries so I need to use pagination. I tried to find tutorials or examples on the internet but I couldn't find any. I managed to develop a datatable with JSON but when I try to add some filters or CRUD modal forms nothing works. Please help, is there any tutorial/example of a Django datatable with server-side processing with all of its functionalities? Thank you! -
Djang+PostgreSQL: Use random of no order is given (in CI)
In CI I want PostgreSQL to order results, if no explicit "ORDER BY" is given. We use Django, but a pure PG-based solution, would be fine, too. Background: All tests where fine because PG always used the same order. But in production we had a nasty bug. I want to catch this in CI (not in production) -
How to show continuous serial number in pagination using django
I have a blog list layout. Now i am using {{forloop.counter}} in my template to generate serial numbers and it is working perfectly. Page 1 shows 1 - 20 serial number, then page 2 shows again 1 - 20 serial numbers. but i want to show serial number from 21 - 40 in page 2 and so on.. instead of 1 - 20 again and again in every page. How to do this using django -
fix long running filter task in django views
input_df = pd.read_excel(uploadedfile) variable_column = code search_type = 'icontains' filter = variable_column + '__' + search_type li = [] for i in input_df["KT_DB"]: qset=KT_DB.objects.filter(**{ filter: i}) df = pd.DataFrame.from_records(qset.values()) li.append(df) frame = pd.concat(li, axis=0, ignore_index=True) with BytesIO() as b: # Use the StringIO object as the filehandle. writer = pd.ExcelWriter(b, engine='xlsxwriter') frame.to_excel(writer, sheet_name = 'Sheet1', index = False) writer.save() filename = 'KW' content_type = 'application/vnd.ms-excel' response = HttpResponse(b.getvalue(), content_type=content_type) response['Content-Disposition'] = 'attachment; filename="' + filename + '.xlsx"' return response here, filter multiple keywords from the database table, it takes more time to execute. getting request time out before function executes. -
Django OneToOneField - Insert Record in another model
I am having the following models. The ItemSettings model has no records inserted initially. I have a html table with a link Rules to insert settings data for each item number in the ItemMaster. While adding ItemSettings details. The ItemSettings model will have its own view to edit the settings details, once inserted. I dont want the ItemNumber to displayed as a select dropdown. There can be only one record in the ItemSettings model. I am unable to achieve adding the record in the ItemSettings models with the below code. What am I doing wrong? Models.py: class ItemMaster(models.Model): project_name = models.ForeignKey(ProjectMaster, null=True, on_delete=models.SET_NULL) item_number = models.CharField(max_length=15, unique=True, error_messages={ 'unique': "This Item Number Already Exists!"}) item_type = models.ForeignKey(ItemType, null=True, on_delete=models.SET_NULL) item_description = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.item_number class ItemSettings(models.Model): item_number = models.OneToOneField(ItemMaster, on_delete=models.CASCADE) low_at = models.FloatField(default=0) minimum_value = models.FloatField(default=0) maximum_value = models.FloatField(default=0) def __str__(self): return str(self.item_number) Views.py: def itemsettings_edit(request, pkey): item_master_data = ItemMaster.objects.get(id=pkey) item_no = item_master_data.item_number form = ItemSettingsForm() if request.method == "GET": return render(request, 'masters/edit.html', {'item_no': item_no}) elif request.method == 'POST': try: item_number = request.POST['item_no'] low_at = request.POST['low_at'] minimum_value = request.POST['minimum_value'] maximum_value = request.POST['maximum_value'] form = ItemSettingsForm(request.POST) ItemSettings(item_number=item_number, low_at=low_at, minimum_value=minimum_value, maximum_value=maximum_value).save() messages.SUCCESS(request, 'Data Saved') except Exception as e: … -
An error occurred (NoSuchBucket) when calling the PutObject operation
I'm trying to upload the images of my django project to s3 bucket. I have the following in my settings DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_ACCESS_KEY_ID = 'my_key_id' AWS_S3_SECRET_ACCESS_KEY = 'my_secret_key' AWS_STORAGE_BUCKET_NAME = 'app_name' AWS_QUERYSTRING_AUTH = False i have this in my aws permisions { "Version": "2012-10-17", "Id": "Policy1665038511106", "Statement": [ { "Sid": "Stmt1665038504281", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::novacreditbank/*" } ] } I keep getting this error NoSuchBucket at /admin/Novaapp/data/1/change/ An error occurred (NoSuchBucket) when calling the PutObject operation: The specified bucket does not exist -
In django project how can i use Jwt's without using django rest framework. Also in need to use a decorator so that i can apply to my whole project [closed]
I am new to django and want to build a website where I can use jwt's without django rest framework... Please let me know if can use pure django and not drf to implement security -
reading .mxd file without need of arcMap software or any others ones
i have many .mxd file need to convert to shapefile (.shp) or JsonObject i want to find a way to do this process by code Not by useing those softwares manually. is there any way? i am using vanilla js for frontend and django-python backed -
Convert flat structure into a hierarchical JSON
I have a complicated database structure with a lot of one-to-many relations. For example. Models: poll qustions One-to-many relation between them. For the fromtend I want to prepare an accurate json. But I want to execute only one request to the database. Therefore from the database I'll extract a flat structure: Poll ID Poll name Candidate ID Candidate name 1 Election 1 Billy the Labourist 1 Election 2 John the Communist 1 Election 3 Peter the Baptist But for the frontend I need an accurate JSON reflecting: Poll: [1, Election [Candidates: [[1, Billy the Labourist], [2, John the Communist], [3, Peter the Baptist]]]] The only possible solution that crosses my mind is to run a loop and just prepare the json "manually". I don't think it is the best solution. Could you tell me what is the most elegant achieve the goal? Some libraries or ready made apps are higly welcome? -
How to implement dependent/chained dropdown in django admin?
I want to implement a dependent/chained dropdown to get showcased in the django admin page, but unfortunately i am not able to get any close to the solution. I have made 3 models namely, State, District and Block with foreign key dependency on each other and also added them to the main Model, which will be displayed in the django admin. I have tried using solutions posted online but none of them helped. Models.py view Django Admin view -
While creating react app getting NPM errors why
When i try to install the new react app, it shows NPM errors where I already installed npm package -
How to create combobox with django model?
i want to create something like a combo box with django model, but i don't find any field type to do that. something like this: enter image description here -
How to extract data in sentiment analysis due to which the sentiment is calculated? (Words which are responsible for sentiment)
For example: I love icecreame -----> here due to love word the data becomes positive sentiment. In the same way how to find the exact words which are responsible for the resulting sentiment. I have written some basic code in python (django framework) related to sentiment analysis in the below way data="Love the new update. It's super fast!" sid_obj=SentimentIntensityAnalyzer() sentiment_dict=sid_obj.polarity_scores(data) negative=sentiment_dict['neg'] neutral=sentiment_dict['neu'] positive=sentiment_dict['pos'] compound=sentiment_dict['compound'] if sentiment_dict['compound']>=0.05: overall_sentiment='Positive' elif sentiment_dict['compound'] <= -0.05: overall_sentiment='Negative' else: overall_sentiment='Neutral' Note: I have imported the packages which are required for the execution of above code and it works. Can anyone pleas help me in adding the important code which extracts the words responsible for the resulting sentiment. -
How to Send Mail Asynchronously Using Django's Async View
I am building a project, and I want to send a notifying e-mail when User takes a specific action. I did some search and managed to achieve this using threading.Thread. Since Django now fully supports async view, I want to do it with async function. Here is what I tried: from asgiref.sync import sync_to_async from django.core.mail import send_mail from django.shortcuts import render from myproj.settings import EMAIL_HOST_USER import asyncio asend_mail = sync_to_async(send_mail) async def index(request): asyncio.create_task( asend_mail( subject='Test', message='Lorem ipsum', from_email=EMAIL_HOST_USER, recipient_list=['ezon@stackoverflow.dummy'] ) ) return render(request, 'myapp/index.html', {}) However, when I request this index page, I still get response AFTER asend_mail coroutine complete. I have tried the following simple async function (from a tutorial), and everything works as expected. async def async_print(): for num in range(1, 6): await asyncio.sleep(1) print(num) async def index(request): asyncio.create_task(async_print()) return render(request, 'myapp/index.html', {}) I wander what is the key difference between the above two scenarios. I am using python 3.10.7, django 4.1.2, daphne 3.0.2 (as the server, NOT django's development server). I am new to async/await feature. I will be appreciate it if someone can give a comprehensive explanation Thanks in advance. -
Django Restframework POST Object with Array of Objects to One-to-Many tables
I'm new to django and I'm trying to find a solution on how to post an object with array of object inside my database. So far, here's my sample model. class Fruit(models.Model): name = models.CharField(max_length=100) class FruitReviews(models.Model): reviews = models.CharField(max_length=100) fruit = models.ForeignKey(Fruit, on_delete=models.CASCADE) Here's my serializer. class FruitSerializer(serializers.ModelSerializer): class Meta: model = Fruit fields = '__all__' class FruitReviewSerializer(serializers.ModelSerializer): class Meta: model = FruitReview fields = '__all__' And Here's my viewset that I'm trying but unfortunately, it doesn't work. @api_view('POST']) def createFruit(request): serializer = FruitSerializer(data=request.data) serializer2 = FruitReviewSerializer(data=request.data.fruitReviews, many = True) if serializer.is_valid() and serializer2.is_valid(): serializer.save() serializer2.save() return Response(status=status.HTTP_200_OK) Basically, for instance, from the client side I want to post something like this { "name": "Apple", "fruitReviews": [{ "reviews": "Very yummy" }, { "reviews": "Healthy" }, { "reviews": "Fresh" }] } I want it to be posted to the fruit table and fruit reviews properly with their relationships as one-to-many intact. Any help please? -
Serving Django static files from private S3 bucket using CloudFront
I am running Django 3.2.16 and Python 3.7.3. I want to serve my static Django files from a private AWS S3 bucket. I am using django-storages 1.13.1 and boto3 1.24.85. I have been following this article: https://shrinidhinhegde.medium.com/how-to-serve-django-static-files-in-a-production-environment-from-a-private-s3-bucket-using-aee840a5a643 I have my S3 and CloudFront infrastructure set up. However, I am having trouble with the AWS_CLOUDFRONT_KEY and AWS_CLOUDFRONT_KEY_ID in my settings.py. I am using python-decouple 3.3. I generated private and public keys with 'openssl genrsa -out private_key.pem 2048' and 'openssl rsa -pubout -in private_key.pem -out public_key.pem' from a cygwin window on my Windows PC. In my .ini file I have the the two keys entered like this: AWS_CLOUDFRONT_KEY=-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAn05f+B/dcarBHa4hTyPCSYgP9x39qnN74yLDmy4QGw8MaRaB lftda77PNuwj/DTjUc59YPlMM8HIS9D436I3ngPEnhn5B3ojfu80xr5zCIZXIynW d827CKjKjaputHQu5L2ef13YYpMqUIaaLuxhvKyVcpla1c1gBPVOlyAe9QWJdazq SrkyHO3DakBfK2bySr433EkYTDx0AwLJ4iVBAuo71pYgRXipJ+G84d9q1kAPK8RU ... UOb3kifExjFSsmtAUgfmog99HOgcdxDkHcMR/FR/0jz6ji0gsE/G4nsQioYYY4Hq bxnZAoGAG/sVbReKOpcHQo4bxJ+F4SzjyN+TQF7rNI3qgUe6S7xlHVsuzPgwPPrv q2Ax8mi24weX4VdxmXupT1rZ+DpNQN2K6YPtn/kaP93oh7dPpoMiC3jmNKUO3Zkr jbj6BO/UbcvI7noxgMTTCjSCHs2/VE6tuOkS635AH6HjO1Ag6i4= -----END RSA PRIVATE KEY----- and AWS_CLOUDFRONT_KEY_ID=-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn05f+B/dcarBHa4hTyPC ... JlEKvnt+sVI5aBI0o9ylSvIHqpnYeN8vsRswRbLUYti9k5wCjrhmKZTH5PudPruw MQIDAQAB -----END PUBLIC KEY----- I am using a tab at the beginning of each continuation line of the two KEYs in my .ini file to satisfy decouple's config. The public key has been added to CloudFront. I read the two keys into my settings.py file with: AWS_CLOUDFRONT_KEY = config('AWS_CLOUDFRONT_KEY') AWS_CLOUDFRONT_KEY_ID = config('AWS_CLOUDFRONT_KEY_ID') That let's me launch the Django app. When I go to the web site, though, I am getting an … -
Javascript this.value onchange not working
I'm trying to get the value of a form input usign JS: HTML: <td onchange="validate_hours(this)">{{ form.monday }}</td> JS: function validate_hours(elem) { console.log(elem.value) } But I receive "undefined", this makes sence to me but doesn't work, any idea about why? I found a solution, I used firstChild to get the input and now is returning the value: JS function validate_hours(elem) { input = elem.firstChild.value console.log(input) } -
How to refresh an id using innerHTML when a button is clicked
I have the following JS code and I am trying to reload the content of the innerHTML not just insert it as it is. Here is the script <button value="true" id="customSwitches">Button</button> <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click','#customSwitches', function(event){ event.preventDefault(); document.getElementById("table").innerHTML = `{% include 'app/table.html' %}`; }, }); }); </script> -
Django Error (admin.E106) ModelInline must have a 'model' attribute
Was just following the tutorials from Django documentation. In Writing your first Django app, part 7, the tutorial was adding the Choice section when a user is adding a Question. In the documentation, the code seems to work fine, but in my system, for some reason it isn't working. Please tell me where I got it wrong. code: from django.contrib import admin from .models import Choice, Question # Register your models here. class ChoiceInline(admin.TabularInline): model: Choice extra: 3 class QuestionAdmin(admin.ModelAdmin): # fields = ['pub_date', 'question_text'] fieldsets = [ (None, {'fields': ['question_text']}), ('Date Information', {'fields': ['pub_date'], 'classes':['collapse']}), ] inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin) Error: <class 'polls.admin.QuestionAdmin'>: (admin.E105) 'polls.admin.ChoiceInline' must have a 'model' attribute. -
Django: RecursionError: maximum recursion depth exceeded while calling a Python object
I'm trying to create a superuser using python manage.py createsuperuser. I got RecursionError: maximum recursion depth exceeded while calling a Python object. Models.py import datetime from django.db import models import uuid from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class UserManager(BaseUserManager): # Creating Super User def create_superuser(self, first_name, last_name, email, password, **kwargs): kwargs.setdefault('is_admin', True) kwargs.setdefault('is_staff', True) kwargs.setdefault('is_active', True) kwargs.setdefault('is_superuser', True) if kwargs.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True' ) if kwargs.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True' ) return self.create_superuser(first_name, last_name, email, password, **kwargs) # Creating User def create_user(self, first_name, last_name, email, username, password, **kwargs): email = self.normalize_email(email) # User Object user = self.model(email=email, username=username, password=password, first_name=first_name, last_name=last_name, **kwargs) # Saving User user.save() return user Admin.py class UserAdmin(UserAdmin): model = User list_display=["first_name", "last_name", "username", "email", "created_time", "last_login"] list_filter = ['is_active', 'is_staff',] admin.site.register(User, UserAdmin) Error Traceback (most recent call last): File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Template\template_layer\manage.py", line 22, in <module> main() File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Template\template_layer\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Template\lib\site- packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Template\lib\site- packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Template\lib\site- packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "D:\Concept_and_Project\Web Development\BackEnd\Django Framework\Template\lib\site- … -
django import_export Users password not encoded
i use library from import_export.admin import ImportExportModelAdmin to make admin enterface get file xls ..csv ..etc so I can enter a lot of data just by entre one file with all data the problem is when I export fill Users and then fail all data I find the password not encoded my admin.py file from django.contrib import admin # Register your models here. from django.contrib.auth.admin import UserAdmin from import_export.admin import ImportExportModelAdmin from student.models import Students, CustomUser class UserModel(UserAdmin): pass class UserModel2(ImportExportModelAdmin): pass admin.site.register(CustomUser , UserModel2) i dont know how to use from django.contrib.auth.hashers import make_password to solve this problem -
Package management issue with Poetry virtual environment and Django
I spent a good deal of time the past two days trying to use poetry correctly. I'm not new to poetry and have used it for a while. But in this DJANGO project I just started with a buddy, after adding packages, some of them needed to be added again via 'python -m pip install '. Once I did that, the django project passed a check and I could also migrate tables. It really bothers me that I'm using a virtual management package that doesn't appear to always work. I like poetry and want to use it. Some of the packages I had to pip install are django and pymysql. I also use pyenv. I'm running python version 3.10.6. I did things such as deleting the .venv folder (mine gets created in the project directory) checking with pip freeze that these packages are not already installed, and then doing a poetry update to re-create .venv. Any suggestions or ideas? I really need to focus on my django project and not be farting around all the time with package issues so I would like to either fix this or at least have a better idea of what is going wrong so … -
docker nginx django gunicorn not serving static files in production
Trying to deploy website with nginx + gunicorn + docker + django. But ngingx isn't serving static files. Following are the configurations: Django project structure settings file production.py STATIC_URL = "/static/" """STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )""" STATIC_ROOT = "/app/forex/static/admin/" Docker file for nginx FROM nginx:1.19.0 COPY ./default.conf /etc/nginx/conf.d/default.conf nginx configurations upstream django { server website:8000; } server { listen 80; client_max_body_size 100M; proxy_set_header X-Forwarded-Proto $scheme; location / { proxy_pass http://django; } location /media/ { alias /app/media/; } location /static/ { alias /app/forex/static/admin/; } } Gunicorn docker file FROM python:3 ADD requirements.txt /app/requirements.txt ADD . /app WORKDIR /app EXPOSE 8000:8000 RUN pip install --upgrade pip && pip install -r /app/requirements.txt RUN python manage.py collectstatic --no-input --settings=forex.settings.production CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "3", "forex.wsgi:application", "DJANGO_SETTINGS_MODULE=forex.settings.production"] docker-compose.yml services: website: build: context: . dockerfile: Dockerfile.app env_file: - env container_name: website_container_8 nginx: build: ./nginx volumes: - static:/app/forex/static/admin/ ports: - "80:80" depends_on: - website volumes: static: FROM nginx container, it isn't copying static files. What do I need to change to make it working?