Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Stripe not working when getting needed variables from means other than GET parameters
I'm trying to submit a payment to Stripe using the documentation here. My goal is to submit a PaymentIntent and then check the status. The payment page I am creating is for a donation, so the amount can vary. As such, I'm trying to read the amount from my Django application into the stripe JS, and this is failing. This is my slightly modified code from the documentation example, which works fine: const items = [{ amount: "20" }]; let elements; initialize(); checkStatus(); document .querySelector("#payment-form") .addEventListener("submit", handleSubmit); // Fetches a payment intent and captures the client secret async function initialize() { const response = await fetch("/payment/intent/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ items }), }); const { clientSecret } = await response.json(); const appearance = { theme: 'stripe', }; elements = stripe.elements({ appearance, clientSecret }); const paymentElement = elements.create("payment"); paymentElement.mount("#payment-element"); } The problem comes when I try to replace const items = [{ amount: "20" }]; Based on this answer, I've tried grabbing the value from a hidden value, by the following (showing hidden field in template and line in JS to obtain value from hidden field): <input type="hidden" id="amount" name="amount" value="20"> and const items = … -
Determine whether 2 files are of similar file extensions in Python
I'm working on a project including a webapp, with the option for storing smaller files. Currently an uploaded file can be updated to a new version IF the format (file extension) of the files are identical. MyPainting.jpg can be replaced by a new file MyPainting2.jpg. To implement this logic I'm simply performing the following check if file_type != local_file_type: return Exception("These files are not of simmilar format") I wish to extend this logic so that .jpg files can also be replaced by .jpeg, ppt can be replaced by pptx and so on. One solution would be to hardcode some collection of simmilar types, but that seems awfully annoying to deal with. TLDR: Does some package, or system exist that can tell me whether or not 2 file extensions are similar? (jpg --> jpeg are similar, but png --> pdf isn't) I'm working in the Django framework, so if I could put some attribute on my HTML input field, that does the same, that would be a solution aswell. Note: It doesn't really matter to me if PNG and JPG are found to be similar. In technical/practical use, I don't actually need the files to be similar, I could update a … -
many-to-many link table - have multiple of FKs linked - general concept question (Django)
While this is Django related it is more of a concept question that is confusing me. I understand how to set this up in Django. I feel I have solved this before but it would have been a while ago and now suddenly I can't wrap my head around it anymore. This seems so simple so surely I must have a blank moment here? Here is a simple example: Pizza and Topings with a trough (m2m link) table that joins both. Question: How can I have multiples of one type linked to an instance of the other without creating additional fields for it? The issue is that those fields are all FK ids of course. I want an option to have unlimited toppings for a Pizza within ONE single column. Is that doable? Pizza Table Pizza A Pizza B Toppings Table Topping 1 Topping 2 Through Table Pizza A | Topping 1 Pizza A | Topping 2 Pizza B | Topping 1 Pizza B | Topping 1 & Topping 2 <<<<<---- how to do this with 1 column instead of 2? The first answer that came to me was to create a list or dict (or similar) within that DB … -
Django Admin Tabural Inline Throwing Error
I have created a Category and Product model when In the product model I have created a category field which is foreign key relation to the category model. class Category(models.Model): name = models.CharField(max_length=100) icon= models.ImageField(upload_to='CategoryIcons/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name Here is the Product Model - class Product(models.Model): title = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') productImages = models.ManyToManyField(ProductImages) price = models.IntegerField() qty = models.IntegerField(default=0) shortDescription = models.TextField(blank=True, null=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.title}{ self.category}' Now when I try to use Django tabural Inline class with it says SystemCheckError: System check identified some issues: ERRORS: <class 'shop.admin.CategoryInline'>: (admin.E202) 'shop.Category' has no ForeignKey to 'shop.Product'. admin.py file code - from django.contrib import admin from .models import Category, ProductImages, Product, Order, Shipping, OrderItem # Register your models here. class CategoryInline(admin.TabularInline): model = Category readonly_fields = ('id', 'created_at') extra = 2 class ProductAdmin(admin.ModelAdmin): inlines = [ CategoryInline, ] admin.site.register(Category) admin.site.register(ProductImages ) admin.site.register(Product, ProductAdmin) admin.site.register(Order) admin.site.register(Shipping) admin.site.register(OrderItem) I am confused that where I am doing wrong as in most of the places I see the same formate and code. Please help me out.