Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django render page then load data from API response
My view is currently waiting for around 1000 synchronous API queries and it takes a few seconds to render the page with all the data. What is the best practice in Django to make this faster or perhaps render a clean page then load data as it fetches. Should I go asyncio, multiprocess, threading, or make API calls using javascript instead of backend and then fill the DOM? -
How to parse a python ibm cloud action function as JS?
I was trying to invoke a json parsed python function on IBM cloudant action function. It give me error message saying that I cant import cloudant. Following is the action function in python that I have created on cloudant: """IBM Cloud Function that gets all reviews for a dealership Returns: List: List of reviews for the given dealership """ from cloudant.client import Cloudant from cloudant.error import CloudantException import requests def main(param_dict): """Main Function Args: param_dict (Dict): input paramater Returns: _type_: _description_ TODO """ try: client = Cloudant.iam( account_name=param_dict["COUCH_USERNAME"], api_key=param_dict["IAM_API_KEY"], connect=True, ) print(f"Databases: {client.all_dbs()}") except CloudantException as cloudant_exception: print("unable to connect") return {"error": cloudant_exception} except (requests.exceptions.RequestException, ConnectionResetError) as err: print("connection error") return {"error": err} return {"dbs": client.all_dbs()} I tried to upload requirements.txt as zip file but did not work. -
Find Connecting Flights in Django
I am trying to make a search to find connecting flights between two airports using Django. I have two flights CCU to DEL and DEL to DXB. But when I search CCU to DXB, it returns an empty QuerySet. .It is not showing any result. # views.py origin = Airport.objects.get(iata_code='CCU') destination = Airport.objects.get(iata_code='DXB') origin_flights = Flight.objects.filter(origin_airport=origin) destination_flights = Flight.objects.filter(destination_airport=destination) connecting_flights = Flight.objects.filter( Q(origin_airport__in=origin_flights.values('destination_airport')) & Q(destination_airport__in=destination_flights.values('origin_airport')) ) print(connecting_flights) The models # models.py class Airport(BaseModel): airport_name = models.CharField(max_length=200) airport_country = models.CharField(max_length=16) iata_code = models.CharField(max_length=3) class Flight(BaseModel): flight_number = models.CharField(max_length=6) origin_airport = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="flight_origin") destination_airport = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="flight_destination") departure_date = models.DateField() I also tried this. origin_iata_code = 'CCU' destination_iata_code = 'DXB' connecting_flights = Flight.objects.filter( Q(origin_airport__iata_code=origin_iata_code) & Q(destination_airport__iata_code__in=Flight.objects.filter( origin_airport__iata_code__in=Flight.objects.filter( origin_airport__iata_code=origin_iata_code ).values('destination_airport__iata_code') ).values('destination_airport__iata_code')) & Q(destination_airport__iata_code=destination_iata_code) ) print(connecting_flights) -
I want to get category id but I get None, what's the problem? Django
models.py class Post(models.Model): news = 'NW' articles = 'AR' POSITION = [ (news, 'Новость'), (articles, 'Статья') ] author_post = models.ForeignKey(Author, on_delete=models.CASCADE) category_type = models.CharField(max_length=2, default=news, choices=POSITION) date_created = models.DateTimeField(auto_now_add=True) category = models.ManyToManyField(Category) title = models.CharField(max_length=128, blank=False, null=False) text = models.TextField(blank=False, null=False) raitingPost = models.SmallIntegerField(default=0, verbose_name='Рэйтинг поста') class Subscription(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='subscriptions') category = models.ForeignKey(to=Category, on_delete=models.CASCADE, related_name='subscriptions') signals.py @receiver(post_save, sender=Post) def subscribe_notify(instance, created, **kwargs): if not created: return print(instance.category) I need to get the category ID of a post that was just created. When I do instance.category I get None, you can see it on the screenshotenter image description here -
Django 1.11 Subquery annotate with .exclude
Is it not possible to exclude inside a queryset? I always receive this error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. The part of the code I am wondering why is it not working: def get_queryset(self): return self.queryset.annotate( foo_count=Subquery( Foo.objects.exclude(code__hash=OuterRef('hash')) .values('code') .annotate(cnt=Count('pk')) .values('cnt'), output_field=IntegerField() ), ) Thanks for any possible solutions! -
Prefetching implicitly related model instances
Let's say I have two models that look like that: class UserRequest(models.Model): # other fields deal_type = models.CharField(choices=DEAL_TYPE_CHOICES, max_length=10) class Company(models.Model): # other fields deal_types_interested_in = ArrayField( models.CharField(max_length=10), ) # this field has a set of choices from DEAL_TYPE_CHOICES As you can see thoses models have no explicit relationship with each other but an "implicit" one via the deal types. What I want to achieve is to query UserRequests and "prefetch" all Companys that have matching deal types. If those two models had a direct relationship (m2m) I could use prefetch_related like that: requests = UserRequest.objects.prefetch_related( Prefetch('companies', Company.objects.filter(deal_types_interested_in__contains=OuterRef('deal_type'))) ) But that doesn't work as there is no relation companies on the UserRequest model. How can I prefetch those Company instances anyways? I especially want the prefetch to only be evaluated when the queryset is evaluated, just like with prefetch_related. In other words I'm looking for a prefetch_related but for implicitly related models with no explicit through table and no predefined relation to each other. In my use case I have even more criteria than only the deal_type to match Companies to User requests but I omitted them for sake of simplicity. -
1048, "Column 'materials' cannot be null"
I have created a model with following fields. But my checkbox is not working. models.py class Student(models.Model): name = models.CharField(max_length=300) # dob = models.DateField(max_length=8) age = models.IntegerField() gender = models.CharField(max_length=300) phn_no = models.IntegerField() email = models.EmailField() address = models.CharField(max_length=300) dept = models.CharField(max_length=300) course = models.CharField(max_length=300,blank=True) purpose = models.CharField(max_length=300) materials = models.CharField(max_length=300) This is the user interface created for my form. student.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="{% static 'css/custom.css' %}" rel="stylesheet" > <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@100&display=swap" rel="stylesheet" > <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" > <!-- <script src="http://kit.fontawesome.com/a076d05399.js"></script>--> <script src="{% static 'js/a076d05399.js' %}"></script> <!-- <meta name="description" content="{% block metadescription%} {% endblock %}">--> <!-- <title>{% block title %}{% endblock %}</title>--> <script> var deptObject = { "Computer Science": ["MCA","BCA","MSc Computer Science", "BSc Computer Science"], "Commerce": ["Mcom", "Bcom", "BBA"] } window.onload = function() { var deptSel = document.getElementById("dept"); var courseSel = document.getElementById("course"); for (var x in deptObject) { deptSel.appendChild(new Option(x, x)); } deptSel.onchange = function() { //empty Chapters- and Topics- dropdowns courseSel.length = 1; //display correct values for (var y in deptObject[this.value]) { courseSel.appendChild(new Option(deptObject[this.value][y], y)); } } } </script> </head> <body> <div class="container"> {% include 'navbar.html' %} <div class="container"> <div class="row justify-content-center"> <div …