Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django signals and channels
i am new with django and django channels i wanna create app and use signals when a user insert new row or order in the database table i send signal to Django channels My application have more than one company so i need filter users only users in the same company see the signal or the event of creating new row or new order of the same company All new order or row can filter by column company to send signal to users of the same company only , May like group every users of the same company Thank a lot -
How To Optimize Django ORM Many-to-Many Relationships?
I am trying to make a large scale REST API app, I came up with a-not-so-good models and maybe even worse serializers that makes 100 of queries per one request for one end point? My question is how to optimize this. this is the models code class MainModel(models.Model): text = models.CharField(max_length=150, unique=True) subclass = models.ManyToManyField(Subclass, related_name='Sclass') Premium = models.BooleanField(default=True) class Meta: indexes = [ models.Index(fields=['text',])] def __str__(self): return str(self.text) class AnotherModel1(models.Model): text = models.CharField(max_length=400, unique=True) mainModel = models.ManyToManyField(mainModel, related_name='mainModel1') def __str__(self): return str(self.text) class AnotherModel2(models.Model): text = models.CharField(max_length=300, unique=True) mainModel = models.ManyToManyField(mainModel, related_name='mainModel2') def __str__(self): return self.text class AnotherModel3(models.Model): text = models.CharField(max_length=300, unique=True) mainModel = models.ManyToManyField(mainModel, related_name='mainModel3') def __str__(self): return self.text class AnotherModel4(models.Model): text = models.CharField(max_length=300, unique=True) mainModel = models.ManyToManyField(mainModel, related_name='mainModel4') def __str__(self): return self.text class AnotherModel5(models.Model): text = models.CharField(max_length=300, unique=True) mainModel = models.ManyToManyField(mainModel, related_name='mainModel5') safety = models.CharField(max_length=20, default='Unknown') def __str__(self): return self.safety and so on for 12 models all linked to MainModel by many-to-many relationships. The request goes to MainModel and I use modelviewset class the view is something like this class MainViewSet(viewsets.ModelViewSet): queryset = MainModel.objects.all() serializer_class = MainSerializer http_method_names = ['get', ] filter_backends = [OrderingFilter] ordering_fields = ['text', ] ordering = ['text'] throttle_scope = 'Main' and the serializer … -
Get data that isn't related with field in other model
I have User, Profile, NotMatches, Matches models. How can I get all the profiles without profiles that are in NotMatches and Matches class NotMatches(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="first_user") not_matched_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="second_user") class Matches(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="match_first_user") matched_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="match_second_user") class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=150, blank=True) My usecase So if you are user and you see something that you like/don't like you dislike/like it. The object is saved to NotMatches/Matches and if you go to the endpoint again you will see all the objects without the one you you interacted with I have the code that saves data etc but I'm struggling with grasping how to query data -
GraphQl Django, how to cache at resolver if Type has custom fields added
scratching my head with this one for the past while but I'm sure I'm just missing something simple. I am using graphene-django and I am trying to also use redis cache. The issue I am having is as follows. I have a model AdDetails class AdDetails(models.Model): id = models.IntegerField(primary_key=True) dealer = models.ForeignKey('DealerLookup', models.DO_NOTHING, db_column='dealer') county = models.ForeignKey('CountyLookup', models.DO_NOTHING, db_column='county') vehicle_type = models.ForeignKey('VehicleTypeLookup', models.DO_NOTHING, db_column='vehicle_type') href = models.TextField() make = models.ForeignKey('MakeLookup', models.DO_NOTHING, db_column='make') model = models.ForeignKey('ModelLookup', models.DO_NOTHING, db_column='model') year = models.ForeignKey('YearLookup', models.DO_NOTHING, db_column='year') mileage_km = models.IntegerField(blank=True, null=True) fuel_type = models.ForeignKey('FuelTypeLookup', models.DO_NOTHING, db_column='fuel_type') transmission = models.ForeignKey('TransmissionLookup', models.DO_NOTHING, db_column='transmission', blank=True, null=True) engine_size = models.ForeignKey('EngineSizeLookup', models.DO_NOTHING, db_column='engine_size', blank=True, null=True) colour = models.ForeignKey('ColourLookup', models.DO_NOTHING, db_column='colour', blank=True, null=True) for_sale_date = models.DateField() sold_date = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'ad_details and in schema.py I have added a few fields to it. class AdDetailsType(DjangoObjectType): price = graphene.Float() previous_price = graphene.Float() price_movement = graphene.Float() def resolve_price(self, info): price_history = self.pricehistory_set.order_by('-date').first() if price_history: return price_history.price return None def resolve_previous_price(self, info): price_history = self.pricehistory_set.filter(price__gt=0).order_by('date').first() if price_history: return price_history.price return None def resolve_price_movement(self, info): price = self.pricehistory_set.order_by('-date').first() prev_price = self.pricehistory_set.filter(price__gt=0).order_by('date').first() if price is not None and prev_price is not None: return price.price - prev_price.price else: return None class … -
how to create hyperlink to specific sections of same page on Django template
I have a website with a blog, I need to have a section of titles that includes hyperlinks (#) to the relevant section on the same page. To this I'm using a template tag as below. myapp/templatetags/custom_filters.py from django import template from django.utils.text import slugify register = template.Library() @register.filter def h3_slug(text): """ Returns a sanitized string that can be used as a slug for an H3 tag. """ return slugify(text) and in my template: <!-- my_template.html --> {% load custom_filters %} <h2>Table of Contents</h2> <ol> {% for h3_text in post.contents %} <li><a href="{% url '#'|add:h3_text|h3_slug %}">{{ h3_text }}</a></li> {% endfor %} </ol> {% for h3_text in post.contents %} <h3 id="{{ h3_text| h3_slug }}">{{ h3_text }}</h3> <p>Content for section {{ h3_text }}</p> {% endfor %} Now the problem is that it is listing all post.contents as Table of Contents !! I don't know how to make it detect only some specific sections like H3 tags as the title and add hypetlink to them using #. -
How to set X-Frame-Options header for uploaded files to S3 Django-storages?
I use DigitalOcean Spaces as a storage for /media/ files in Django using django-storages. I need files to send X-Frame-Options:'ALLOWALL' when they are fetched from Spaces so they can be displayed in iframe. How can I do that? U use boto3 Doesn't work: AWS_HEADERS = { "X-Frame-Options": "ALLOWALL", } Returns error when uploading file: AWS_S3_OBJECT_PARAMETERS = { 'X-Frame-Options': 'ALLOWALL' } Error: Invalid extra_args key 'X-Frame-Options', must be one of: ACL, CacheControl, ChecksumAlgorithm, ContentDisposition, ContentEncoding, ContentLanguage, ContentType, ExpectedBucketOwner, Expires, GrantFullControl, GrantRead, GrantReadACP, GrantWriteACP, Metadata, ObjectLockLegalHoldStatus, ObjectLockMode, ObjectLockRetainUntilDate, RequestPayer, ServerSideEncryption, StorageClass, SSECustomerAlgorithm, SSECustomerKey, SSECustomerKeyMD5, SSEKMSKeyId, SSEKMSEncryptionContext, Tagging, WebsiteRedirectLocation -
SerDe problem with django rest framework and foreign key
Context: I have written a simple django rest framework app as BE and a react JS app as FE. The db is SQLite and it's gonna stay that way, since there are only 2 simple models and the number of users will be quite limited as well. For the sake of the example let's assume there is only one team currently with name="First" and id=1. Requirements: display in a table the list of players with team as a name, not its id. add players from form Code: models.py class Player(models.Model): first_name = models.Charfield(max_length=50) last_name = models.Charfield(max_length=50) team = models.ForeignKey(Team, on_delete=models.SET_NULL, blank=True, null=True) class Team(models.Model): name = models.Charfield(max_length=50) def __str__(self): return f"{self.name}" views.py class PlayersView(APIView): def post(self, request): serializer = PlayerSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) In order to meed 1st requirement I've implemented serializer like this: serializers.py class PlayerSerializer(serializers.ModelSerializer): team = serializers.CharField(source="team.name", read_only=True) class Meta: model = Player fields = "__all__" That worked fine, but I wasn't able to add the players to the database when processing the request from the FE. The body of that POST request is: body { "first_name": "John", "last_name": "Doe", "team": 1 } Looking on SO I found: Retrieving a … -
I can't send the image in my Django chat application
Hello everyone. This is my first time asking a question on StackOverFlow, so I may not explain properly... I am developing a Django chat website, where two users can send message with each other. I can send message without any problem, but I have issue with sending images. I simply can't receive any image. Here is my model.py: class ChatMessage(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="received_messages") message = models.TextField(null=True, blank=True) image = models.ImageField(null=True, blank=True, upload_to="message-images/") updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] Here is my views.py: @login_required(login_url='login') def chatUser(request, pk): sender = User.objects.get(pk=request.user.id) receiver = User.objects.get(pk=pk) form = ChatMessageForm() if request.method == 'POST': form = ChatMessageForm(request.POST, request.FILES) if form.is_valid(): message = form.save(commit=False) message.user = request.user message.receiver = receiver sender.profile.chatters.add(receiver) receiver.profile.chatters.add(sender) message.save() return JsonResponse({'success': 'Message sent successfully'}) context = { 'receiver': receiver, 'messages': messages, 'form': form, } return render(request, 'base/chat.html', context) Here is my forms.py: class ChatMessageForm(forms.ModelForm): class Meta: model = ChatMessage fields = ('message', 'image') labels = { "message": "", } Here is my template: <form method="POST" action="" enctype="multipart/form-data" > {% csrf_token %} <textarea type="text" name="message" placeholder="Send Message..." rows="2" autocomplete="off" class="form-control border-own-left border-own-right border-own-top" style="border-bottom: none; border-radius: 0%;" oninput="autoExpand(this)"></textarea> <div class="d-flex justify-content-between bg-white … -
Virtual environment and django is not created in my directory. Python 3.11
PS C:\Users\38099\Desktop\courses> pipenv install django==4.0.8 Creating a virtualenv for this project... Pipfile: C:\Users\38099\Pipfile Using C:/Users/38099/AppData/Local/Programs/Python/Python311/python.exe (3.11.1) to create virtualenv... [ ] Creating virtual environment...created virtual environment CPython3.11.1.final.0-64 in 501ms creator CPython3Windows(dest=C:\Users\38099.virtualenvs\38099-inBhiGOL, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\38099\AppData\Local\pypa\virtualenv) added seed packages: pip==23.0, setuptools==67.1.0, wheel==0.38.4 activators BashActivator,BatchActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator Successfully created virtual environment! Virtualenv location: C:\Users\38099.virtualenvs\38099-inBhiGOL Installing django==4.0.8... Resolving django==4.0.8... Installing... Adding django to Pipfile's [packages] ... Installation Succeeded Installing dependencies from Pipfile.lock (664a36)... To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. I need to install virtual environment and django version in my directory "C:\Users\38099\Desktop\courses>". But every time the location of VE is " C:\Users\38099.virtualenvs\38099-inBhiGOL". pipenv in my powershell is installed. I also have folder '.venv' in my explorer, but it ignores it anyway, choosing different location -
Using Drawflow library create nodes but they are not visible
I'm trying to use the amazing Drawflow library (Javascript) from: https://github.com/jerosoler/Drawflow Here is my code: <head> {% load static %} <link rel="stylesheet" href="{% static 'drawflow/src/drawflow.css' %}"> <link rel="stylesheet" href="{% static 'css/theme.css' %}"> </head> <body> <div id="drawflow"></div> <script type='module'> // The minified version is build as an UMD module, so it cannot be imported // It should be rebuild eventually. // https://stackoverflow.com/questions/75514648/uncaught-syntaxerror-the-requested-module-does-not-provide-an-export-named-dra import Drawflow from "{% static 'drawflow/src/drawflow.js' %}"; import sheet from "{% static 'drawflow/src/drawflow.css' %}" assert { type: 'css'}; import { h, getCurrentInstance, render } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js' const Vue = { version: 3, h, render }; const container = document.getElementById("drawflow"); var editor = new Drawflow(container); //const internalInstance = getCurrentInstance() //editor.value = new Drawflow(container, Vue, internalInstance.appContext.app._context); editor.reroute = true; editor.editor_mode = 'edit'; editor.start(); editor.addModule('nameNewModule'); const nodeData = { id: 'node-1', name: 'My Node', module: 'nameNewModule', x: 500, y: 100, class: '', html: function() { return '<div>' + this.name + '</div>'; } , inputs: { input_1: { label: 'Input 1', }, }, outputs: { output_1: { label: 'Output 1', }, }, data: { command: 'Run command', }, }; editor.addNode(nodeData.module, Object.keys(nodeData.inputs).length, Object.keys(nodeData.outputs).length, nodeData.x, nodeData.y, nodeData.class, nodeData.data, nodeData.html()); </script> </body> However, when I run this (using a Django server), I don't get any error, … -
Django application page styling, flex, responsive
I'm building an app with Django. The functional side is quite tackled, but I want to style the pages and fell into a css nightmare. I'm more a database/python guy than a web designer and not very good in css/flex. I added some of my own css files to the base.html templates in admin and my app's and I get the colors/background I want but I seem to have broken the element layout. What is the proper way to override Django's default styling without breaking the layout? Also can you recommend some debugging tools? The integrated google DevTools helps but is a bit cumbersome. Have any good learning sites recommendations? I know about the W3 schools etc.. but I have trouble linking their info with what I see in django... From what I read, responsive design is the way to go if I want to have my site display on all sorts of devices, and "progressive enhancement" is a good thing, so I'd like to go in that direction. My development environment is linux Ubuntu. Many thanks -
Django - pass variables into template from {% include %}
In my django project I have a html file that contains a frequently used block of code that creates a container of an item displaying all of the items info. I would like to pass the item variable (from the for loop) from the parent html file to the code that is generated inside the {% include %} tag. I tried using with but to no avail. parent html file <section> {% for item in items1 %} {% include 'App/item_container.html' with item=item %} {% endfor %} </section> App/item_container.html <div class="item-container"> <h1>{{item.item_name}}</h1> <p>{{item.info}}</p> </div> -
Expired tokens are not deleted after expiration in django-rest-knox 4.1.0
I am using django-rest-knox 4.1.0 . In its documentation it says that expired tokens are deleted automatically. But it is not deleting the tokens. In settings.py I gave 10 minutes for expiration of token (for testing purposes). "TOKEN_TTL": timedelta(minutes=10) I check the database after that time, they are not deleted. pgadmin knox token table Also I try to send request with those expired tokens, the respond is successful. -
django_elasticsearch_dsl why define a Model?
I am using django_elasticsearch_dsl in my django application. #documents.py from django_elasticsearch_dsl import Document, Index, fields from .models import Article test_index = Index('test') @test_index.doc_type class LingualiDocument(Document): captured_time = fields.DateField(index=False, doc_values=False) text = fields.TextField() class Django: model = None class Index: name = 'test' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, 'routing.allocation.include._tier_preference': 'data_content' } Why does Django not allow this? It seems that it is forcing me to define a Model as well? Isn't the whole point of elasticsearch not to use a relational database? It seems a bit redundant having to specify a Model definition which is almost identical to the document definition. Best, Andy -
I have test for python for below use case using Python Django, can someone answer
Users should be able to upload the PDF file in UI. Post upload we should show the PDF on the left side of the screen along with a text box on top. User should be able to enter some keywords in the text box and we should match the keywords and show the matching sentences in the grid along with page number. On clicking the matching sentence we should highlight the sentence containing the keyword. I have tried with django framework using html file but point 3 is not getting resolve -
Django admin panel issue
I created two projects in django and in first project's admin panel has button "Save as new" but second app not? How is it possible? -
Trying to run a python program but I keep getting file is not a package error
I've got a python program "LoginServiceBase.py" Defined inside a directory called 'LoginService'. I've created an __init__.py file that looks like this: # Import views and other necessary modules from .views import LoginView, SignupView from .LoginServiceBase import settings # Define package-level variables APP_NAME = 'LoginServiceBase' My LoginServiceBase.py uses Django. I've set up a class inside LoginServiceBase for my Django settings. When I attempt to run python -m LoginServiceBase, I get the following error: ModuleNotFoundError: No module named 'LoginServiceModule.settings'; 'LoginServiceModule' is not a package The LoginView and SignupView classes are defined in the same directory and are contained in a file called 'views.py'. Where is the name 'LoginServiceModule' coming from? I haven't defined it anywhere. Is this a required naming convention for Python packages? Any help appreciated. -
Command not printing output with prefix
I have a helper script that starts my frontend and backend server with one command. To easily see what output is produced by which server, I tried adding a prefix to the output. It works well for the frontend server command yarn dev (for Next.js next dev), but not for the backend. What happens is that stderr gets printed out right away (with the prefix), but stdout only at the point where I stop my script with Ctrl+C, although the ouput contains the prefix. Any idea as to what's causing this behaviour? poetry run python manage.py runserver > >(sed "s/^/[prefix]/") 2> >(sed "s/^/[prefix2]/" >&2) -
Celery using 100% CPU usage on AWS EC2
I have a web app running on an Linux 2/3.4.0 EC2 instance which is deploying slowly (eb deploy), and taking a long time for pages to load. When I eb ssh into the instance, I run top and see two celery instances, each taking 45-60% of CPU usage. -
Django Getting apache default page using ssl certificate
I have my Django project with an SSL certificate from Let's Encrypt, deployed on an Ubuntu 22.04 (LTS) x64 virtual machine from Digital Ocean. When I navigate to the page using my domain, it redirects me to my page correctly, but when I use the IP address, it redirects me to the apache default page. I have a PTR record active on the Digital Ocean site: IPv4: ip address ....... AddressPTR Record: www.mydomain.com. The ip address added to the ALLOWED_HOSTS var on my settings.py: ALLOWED_HOSTS = ['www.mydomain.com', 'my ip address'] What I have in /etc/apache2/sites-available/my_project.conf: <VirtualHost *:80> ServerName mydomain.com ServerAlias www.mydomain.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html RewriteEngine on RewriteCond %{SERVER_NAME} =www.mydomain.com [OR] RewriteCond %{SERVER_NAME} =mydomain.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] The traffic allowed in my server: Status: active 22/tcp ALLOW Anywhere 80/tcp ALLOW Anywhere Apache Full ALLOW Anywhere 22/tcp (v6) ALLOW Anywhere (v6) 80/tcp (v6) ALLOW Anywhere (v6) Apache Full (v6) ALLOW Anywhere (v6) Before getting the SSL certificate, it worked using the ip address as well but, when I set the certificate, it just returns the apache default page. I set the certificate following this five step tutorial: https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-22-04 I hope that's the right information in order to get an answer, … -
Celery doesn't connect Redis
I keep getting the following error: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379/0: Error 99 connecting to localhost:6379. Cannot assign requested address.. I checked everything and can't find the answer why it's happening. I have docker container running for Redis and Celery Broker, and I can see that Celery accepts tasks but can't connect to Redis and doesn't turn task over for following execution. Here's my __init__ file as per the Celery docs: from .celery import app as celery_app __all__ = ('celery_app',) In the celery.py I have following code: import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('Notification') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.conf.task_default_queue = 'notification' app.autodiscover_tasks() This is my Redis connection in settings.py: class RedisConfig(BaseModel): host: str = "redis" # name of container port: int = 6379 db: int = 0 class Config: arbitrary_types_allowed = True def get_redis_connection_str(self) -> str: """ Return redis connection string """ return … -
Django - how to filter OneToMany relationship on same instance
Lets assume I have the same models file class modelA(models.Model): b_model = models.ForeignKey(modelB, related_name='modelA') ... class modelB(models.Model): Where modelB can have multiple instances of modelA related to him, If I perform the following code: outcome = B.objects.filter(modelA__in=[1,2,3]) Should B object will return if any of his modelA in [1,2,3] or all of his modelA in [1,2,3]? I want the second option, how can I achieve it? Another question regarding this code: outcome = B.objects.filter(modelA__gt=1, modelA__lte=3) I want to check the condition on the same instance of modelA, how can I do that? Thanks a lot! I looked everywhere online and couldn't find a solution, hope you can help me -
Send email with pandas dataframe using Django render_to_string
I am trying to send an email with Django and an inserted dataframe but I can't manage to show the style of the Dataframe. I run the code using python manage.py runscript send send.py import pandas as pd from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils.html import strip_tags def run(): df = ... html_content = render_to_string('email.html', {'df':df_html.to_html(index=False)}) text_content = strip_tags(html_content) res = send_mail( 'Dataframe', text_content, 'origin@email.com', ['destiny@email.com], fail_silently=False, ) email.html <body style="color:blue"> {{df|safe}} </body> The email is sent but the table shows no format at all, not as shown in https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_html.html. Anyway, I can't even add the inline css to the email. I searched in Stackoverflow and I found there are some problems with adding css to render_to_string (Django - render to string fails to load CSS) but I can't find any solution. Any idea? Thanks! -
Axios django problem not response status in interceptor.response
// Add a 401 response interceptor window.axios.interceptors.response.use(function (response) { return response; }, function (error) { if (401 === error.response.status) { // handle error: inform user, go to login, etc } else { return Promise.reject(error); } }); "Network Error" without any response It was a problem with CORS and how it was setup, so axios never got the information back from the browser. You have to sort it out from the server side. -
Who to execute request from user's ip and user agent(not server's)?
I have a Django app deployed on server. The application has code that makes requests to the unofficial Instagram API. Since the requests are made from the ip and user agent of the server, Instagram perceives this as a suspicious login attempt. Is there a way to make API requests using the ip and user agent of the user who clicks the button? I am expecting to somehow get data from API when the request was executed from user's ip and user-agent