Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django project files handling logic (fresher question)
In my django project I want user to have an option to upload csv file, than I want to extract data from it , process them and send back processed csv file to user. I would like to know where do I need to implement the logic of file processing in modules or views? -
ImportError: cannot import name dataclass_transform
This is the error message i am getting. Havent seen this error and have no idea how to solve it. ImportError: cannot import name dataclass_transform 2023-01-18 15:07:57.908318: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory 2023-01-18 15:07:57.908340: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. Traceback (most recent call last): File "start_information_extractor.py", line 6, in <module> from queue_handler.document_queue_listner import DocumentQueueListner, QueueConfig File "/home/qburst/CVParsing/queue_handler/document_queue_listner.py", line 14, in <module> from main.billparser import MachineGeneratedBillExtractorPipeline File "/home/qburst/CVParsing/main/billparser/__init__.py", line 4, in <module> from main.billparser.models.bill_info_extractior import MachineGeneratedBillExtractorModel File "/home/qburst/CVParsing/main/billparser/models/bill_info_extractior.py", line 5, in <module> from main.billparser.models.qa_model import BillExtractorQAModel File "/home/qburst/CVParsing/main/billparser/models/qa_model.py", line 3, in <module> from haystack.nodes import TransformersReader File "/home/qburst/CVParsing/.env/lib/python3.8/site-packages/haystack/__init__.py", line 20, in <module> from haystack.schema import Document, Answer, Label, MultiLabel, Span, EvaluationResult File "/home/qburst/CVParsing/.env/lib/python3.8/site-packages/haystack/schema.py", line 24, in <module> from pydantic import BaseConfig, Field File "pydantic/__init__.py", line 2, in init pydantic.__init__ # File "pydantic/dataclasses.py", line 39, in init pydantic.dataclasses # +=========+=========================================+ ImportError: cannot import name dataclass_transform can anyone help? -
HTMX can trigger without attributes like hx-post-get-put...?
I have a form like below. if "Cancel Request" is clicked in the form, "delete__product" will be deleted. my problem here is that htmx cannot work without (I hope not) a process like hx-post-get.... is there a solution for this? ` {% csrf_token %} Are you sure you want to delete ""? Cancel Request Delete ` -
How to fetch data (1+ lac records) from mysql using django
How to fetch data (lac of records) from mysql within seconds? I am using pagination concept but its taking more time for displaying data in html, how to solve this problem. using paginantion or any library. I used orm query for fetch data from table. -
Migrate django database to existing one
So I am using Django with mysql database (most basic tables, like auth, user, admin and few custom models) but I need to migrate those tables with data to a existing PostgreSQL database. The issue is that there are tables created there already. Should I create additional models in the models.py file for those models existing in the database already so that migrations will be applied correctly? I am trying to figure what are the steps that I should take to properly switch databases in the Django app. So far what I have done is saved the data from current (mysql) database: python manage.py dumpdata > dump.json Now the next step I took was to change database in settings.py to postgres. After this I save current table schemas using inspectdb. Here is where I want to ask what should be next steps(?) Merge old and new models.py files. Apply migrations Add data from json dump file to the new database. -
about accessing li but not ul inside the li
im trying to access the text content that is "education" in the code that is written in a li element but not the text content that are written inside the ul of that li element. Basically li has uls and i just want to access li content and not ul's. <span class = "navs nav category">Category</span> <div> <ul class="dropdown-items"> <li class="">Education</li> <ul class="dropdown-items"> <li class="Education">Science</li> <ul class="dropdown-items"> <li class="Science">>Physics</li> <li class="Science">>Chemistry</li> <li class="Science">>Biology</li> </ul> </li> </ul> </li> <li class="">>Entertainment</li> <li class="">>Spiritual</li> </ul> </div> this is my html actually this come out dyanamically because of following code in template: <ul class="dropdown-items"> {% for cat in cats %} {% if not cat.children.all %} <li class="{{cat.parent.name}}">>{{cat.name}}</li> {%else%} <li class="{{cat.parent.name}}">{{cat.name}}</li> {% include "blog/category.html" with cats=cat.children.all %} </li> {% endif %} {% endfor %} </ul> -
Objects are not being displayed to the front end as soon as i use context_object_name in django
I was trying to display a list of items on the front end of a project using Django. I successfully did it and could see the objects in a list upon spinning up the server. But as soon as I used context_object_name in the views.py file, and then check the page, the objects are not appearing. Also, there is no error shown in the terminal and the docker logs too. Here's my Views.py file from django.shortcuts import render from django.views.generic import ListView from .models import Book # Create your views here. class BookListView(ListView): model = Book context_object_name = 'book_list' template_name = 'books/book_list.html' Here's the models.py file from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.title Here's the book_list.html file <!--templates/books/book_list.html--> {% extends '_base.html' %} {% block title %}Books{% endblock title %} {% block content %} {% for book in book_list %} <div> <h2><a href="">{{ object.title }}</a></h2> </div> {% endfor %} {% endblock content %} -
Django Ninja API schema circular import error
I have UserSchema: # users/models.py class User(AbstractUser): ... # users/schemas.py from typing import List from tasks.schemas import TaskSchema class UserSchema(ModelSchema): tasks: List[TaskSchema] = [] class Config: model = User ... ...and TaskSchema: # tasks/models.py class Task(models.Model): ... owner = models.ForeignKey(User, related_name="tasks", on_delete=models.CASCASE) # tasks/schemas.py from users.schemas import UserSchema class TaskSchema(ModelSchema): owner: UserSchema class Config: model = Task ... But it throws: ImportError: cannot import name 'TaskSchema' from partially initialized module 'tasks.schemas' (most likely due to a circular import) (/Users/myname/codes/django/ninja-api/tasks/schemas.py) What I want to do is that I want to fetch: GET /api/todos - a list of tasks with related owners GET /api/todos/{task_id} - a task with owner GET /api/users/{user_id} - a user with a list of owned tasks Versions: python = ^3.11 django = ^4.1.5 django-ninja = ^0.20.0 Please let me know if you need more information. -
Why Popen.communicate returns the satus of another subprocess.Popen?
I have codes that starts Django server and React server at the same time. Here are the codes: back_server.py import os import subprocess def run_server(): current_dir = os.getcwd() target_dir = os.path.join(current_dir, 'marketBack/BackServer') subprocess.Popen(['python', f'{target_dir}/manage.py', 'runserver'], universal_newlines=True) front_server.py import os import subprocess def run_server(): current_dir = os.getcwd() target_dir = os.path.join(current_dir, 'marketPlaying/market-playing') os.chdir(target_dir) process = subprocess.Popen(['npm', 'start'], universal_newlines=True, shell=True) return process server.py import back_server import front_server def run_server_all(): back_server.run_server() front_server.run_server().communicate() run_server_all() When I check the status of the front_server using subprocess.communicate(), it also returns the output of the back_server. Doesn't subprocess.Popen create independent process? Why does front_server.run_server().communicate() returns the status of back_server too? -
Why using anchor tags directly doesn't work and what is the solution
How to work with anchor tags in django?I mean what things should i include in url to make it working .Say I have home,about and contact page.When I go to about and contact error pops up but home seems to work just fine. I tried including all of home,contact and about in the same render method but I guess it's incorrect -
Django doesn't import UserCreationForm
I try to import UserCreationForm from django.contrib.auth.forms. However I got en error like this: ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. What does this mean? I follow this question. However in my wsgi.py file this kind of settings were set up. What should I do? UPDATE: The same error raises when I try to run this code: from django.contrib.auth.models import User. -
Getting ChromeDriver from Selenium
I'm dockerizing my Python-Selenium application, and have this three lines in my Dockerfile: RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - RUN sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' RUN apt-get update -qqy --no-install-recommends && apt-get install -qqy --no-install-recommends google-chrome-stable While outside Docker it works okay, when running selenium inside Dockerized app I get this error: (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.) I'm initializing my selenium function with this code, but I guess when Dockerizing it the service part may need to change? Anyone can guide? def function_scrap(data1): # op = webdriver.ChromeOptions() # op.add_argument('headless') chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chrome_prefs = {} chrome_options.experimental_options["prefs"] = chrome_prefs chrome_prefs["profile.default_content_settings"] = {"images": 2} driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=chrome_options) -
Django update database each second
I'm trying to update Django's project database each second. For now, I can deal with Javascript's function setInterval in my template html but each time I refresh the page or reload my server the values restarts at my database values. I think it could be better to deal that directly in the views.py and then call the variables in my html but got no idea how I can do an incrementation each sec in that way. here is my code using Javascript's function setInterval : #models.py class materiaux(models.Model): nom = models.CharField(max_length=100) nombre = models.IntegerField() production = models.IntegerField() class Meta: ordering = ['id'] def __str__(self): return str(self.nom) #views.py def objetUpdate(request): items = materiaux.objects.all() for item in items: if item.nom == "objet1": nombre_objet1 = item.nombre production_objet1 = item.production if item.nom == "objet2": nombre_objet2 = item.nombre production_objet2 = item.production if item.nom == "objet3": nombre_objet3 = item.nombre production_objet3 = item.production return render(request, 'materiaux.html', {'nombre_objet1': nombre_objet1, 'production_objet1':production_objet1, nombre_objet2': nombre_objet2, 'production_objet2':production_objet2, 'nombre_objet3': nombre_objet3, 'production_objet3':production_objet3}) #materiaux.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>{% block title %}Matériaux{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> <script> var nombreObjets1= {{ nombre_objet1 }}; var nombreObjets2= {{ nombre_objet2 }}; var nombreObjets3= {{ nombre_objet3 }}; var productionObjets1 … -
How To Make Auto Blogger using Python for django bloging website
I want to create an auto blogger for my website. I use react and Django REST to build my website. The auto blogger will copy the article with an image from another blog website and post it on my website. Example: WordPress auto blogger plugin. Click here --> wordpress auto blogger package -
Fernet cryptography.fernet djnago
I am using cryptography.fernet in my views.py and I get this error: File "C:\Users\DIDAM\Desktop\venv\Lib\site-packages\rest_framework\relations.py", line 190, in get_attribute return super().get_attribute(instance) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DIDAM\Desktop\venv\Lib\site-packages\rest_framework\fields.py", line 479, in get_attribute raise type(exc)(msg) AttributeError: Got AttributeError when attempting to get a value for field `course` on serializer `SectionSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'course'. [18/Jan/2023 09:01:55] "GET /api/chapter-section-list/1/ HTTP/1.1" 500 140636 -
how to pass Two params value in one url
event_category = self.request.query_params.get('event_category').split(',') event_subcategory = self.request.query_params.get('event_subcategory') AttributeError: 'NoneType' object has no attribute 'split' i passing event_subcategory params..i get AttributeError: 'NoneType' object has no attribute 'split' -
python django landscape page generating pdf report
I am working on a django project and I have already created PDF report but I want landscape page because some data is hiding after generating PDF report: views.py: def export-pdf(request): response = HttpResponse(content_type = 'application/pdf') response['Content-Disposition'] = 'inline; attachment; fileName=ABC Reports' +\ str(datetime.datetime.now())+'.pdf' response['Content-Transfer-Encoding'] = 'binary' html_string = render_to_string('enroll/pdf-output.html', context) html = HTML(string=html_string) result = html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) return response I have shared the image of pdf report where you can see that status column and its related data is hiding, therefore I need landscape page or an arrangement of page by hard code where I can adjust the pdf report page according to my need. -
Django+AlpineJS : fetching ForeignKey object data with x-init and x-data and iterating over it
(edit, the post formatting got messed up, ugh) I have 2 models, Band (has parameters name, genre, country) and Album (has a band ForeignKey, and other parameters - name and year), and I'm trying to serialize it with AlpineJS so that I have a page displaying a list of bands with a list of corresponding albums beside them. I can do it normally without Alpine, but for this case I need to build a filtering search (like by genre or year, but that's not the current issue) with Alpine so I just have to use it. I also know how to fetch data of objects from one model, but when it's two of them within the same x-data div I'm at loss. Perhaps is there a way of making one single function that has both all Band AND Album data? But then how would I list them beside each other if there's no id requested, I don't know. Damn I get lost at this though I understand all these object relations for the most part. The code below is what I have right now. Tried this, the inner x-for loop doesn't work, but it works fine without it, i.e. if … -
How to implement navigation DB data in Django?
got this code from a friend, we use django and bootstrap to make a rather simple site that displays job offers, until now we displayed the job offers in a row and each offer had a button "apply" that sent the resume etc.. But we would like to change that and only display one job at a time, each job would have 2 buttons "apply" and "next". We tried in a barbaric way to do all this but we have a problem, the next button works well thanks to a little javascript incorporated by my friend but the "apply" button we would like to move to the next offer after clicking on it, for now it only applies we can't get it to display the next offer, how to do? Thank you very much for simplifying your answers I am a beginner in web development, here is the code of my Django template: {% extends 'base2.html' %} {% load static %} {% block title %} Dashboard {% endblock %} {% block content %} <body class="hold-transition light-mode layout-fixed layout-navbar-fixed layout-footer-fixed"> <div class="wrapper" > <div class="content-wrapper" > <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> … -
Inline Images are also being attached
I am using templated_email package to send emails and embedding images using the below code block. Inline images are also being added as attachments in some devices. I don't want them to added as attachments. Is there any solution? with open(path_to_img, 'rb') as image: image = image.read() inline_image = InlineImage(filename=image_name, content=image) This is the documentation of the templated_email package https://pypi.org/project/django-templated-email/#:~:text=with%20open(%27pikachu.png%27%2C%20%27rb%27)%20as%20pikachu%3A I found a solution where if we use MIMEMultipart('related') it will solve the issue if we are using MIME to embed images directly. I want to implement the same while using Django's templated_email package. -
ferrocarrilFormulario() missing 1 required positional argument: 'request'
I need help with my code, I'm making a form in django and I can't solve this error. views.py: def ferrocarrilFormulario(request): if request.method =="POST": miFormulario = ferrocarrilFormulario(request.POST) print(miFormulario) if miFormulario.is_valid: informacion = miFormulario.cleaned_data ferrocarril = ferrocarril(request.POST["tipo"], request.POST["precio"]) ferrocarril.save() return render (request, "AppCoder/inicio.html") Forms.py: from django import forms class ferrocarrilFormulario(forms.Form): tipo= forms.CharField() precio = forms.IntegerField() Form HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Agrega un ferrocarril</title> </head> <body> {% if.miFormulario.errors %} <p style="color: red;"> Datos mal ingresados</p> {% endif %} <form action="" method="POST"{% csrf_token %} <table> {{ miFormulario.as_tabble }} </table> <input type="submit" value="Enviar"> ></form> </body> </html> urls.py: from django.urls import path from AppCoder import views urlpatterns = [ path('',views.inicio, name="Inicio"), path("ferrocarril/", views.ferrocarril, name="ferrocarril"), path("vias/", views.vias, name="vias"), path("manodeobra/", views.manodeobra, name="manodeobra"), path("tables.html/", views.tables, name="tables"), path("ferrocarrilFormulario/", views.ferrocarrilFormulario, name="ferrocarrilFormulario") thank you <3 I wanted the form to work after that, but that is not the case. PS: if I put the request, it generates another error, and in the tutorial it appears without the request. Thanks again. -
How can I sort by calculated fields in Django Admin?
I have a calculated method in my model, and in admin page want to add sort functionality for that calculated field. For now, I am using aggregation for model calculated fields and displaying that in admin. How can I add sort function for this field in admin page? class CoinWallet(Account): student = models.OneToOneField( 'students.Student', on_delete=models.PROTECT, related_name="coinWallet", null=True) @admin.display(description='Total Coins') def total_coins(self): positive_movements_aggregate = self.movement_set.filter( side=self.positive_side, ).aggregate(models.Sum('amount')) positive_movements_balance = positive_movements_aggregate[ 'amount__sum'] if positive_movements_aggregate['amount__sum'] else 0 return f'{positive_movements_balance}' @admin.register(CoinWallet) class CoinWalletAdmin(admin.ModelAdmin): list_display = ('id', 'student', 'balance', 'total_coins', 'answer_coins', 'bonus_coins', ) search_fields = ('id', 'student') def get_queryset(self, request): queryset = super(CoinWalletAdmin, self).get_queryset(request) queryset = queryset.annotate(_total_coins=ExpressionWrapper(F('balance'), output_field=DecimalField())).order_by('_total_coins') return queryset def total_coins(self, obj): return obj._total_coins total_coins.admin_order_field = '_total_coins' I tried this, but, instead of balance, i want to add sortable for total_coins. What should I do in this admin class? -
What is the best way to send field values for model creation in URL in DRF?
I have and app with books, where I want to have POST request with field's value in URL like POST URL:BOOKS/NINETEEN_EIGHTY_FOUR HTTP/1.1 content-type: application/json { "description": "my favorite book" } RESPONSE { "description": "my favorite book", "book_name": "NINETEEN_EIGHTY_FOUR" } What is the best way to do it in DRF? I have my book model with 2 field: description and book_name And in my views.py I have viewset (connected to router book) which is working with books: for example GET books/ will return full list of books and through @action decorator I get GET/POST books/{book_name} requests class BookViewSet(ListViewSet): queryset = Book.objects.all() serializer_class = BookSerializer @action(methods=['get', 'post', ], detail=False, url_path=r'(?P<book_name>\w+)',) def get_or_create_book(self, request, book_name): if request.method == 'GET': book = get_object_or_404(Book, book_name=book_name) etc book, create = Book.objects.get_or_create(book_name=book_name) Are there something better ways? -
Request.urlopen does not work after moving the server to the cloud. use docker-compose django, nginx
Yesterday, I moved to the cloud while running the server locally. Based on ubuntu 20, the server is operated using docker, django, nginx, mariadb, certbot in docker-compose. is configured and operational. It has opened both 80:port and 443post to the cloud, and outbound is allowed in the cloud itself. In docker-compose, if you receive a request from 80 or 433 from nginx.conf to upstream django_nginx server container name: 8000 after mapping from docker-compose to 80 or 433 for the application --bind 0.0.0.0:8000 Jango. Proxy_pass http://django_nginx; is passing. The problem is that when an external api is called from a running django inside the docker container (e.g. request.urlopen(url) header included or not included), there is no response. So I gave the option request.url, timeout=3 and checked, and the https request causes We failed to reach a server /Reason: _ssl.c: 980: The handshake operation timed out http request causes We failed to reach a server /Reason: timed out. I used to run a server locally as a virtual machine, but it was a logic that was going on without a problem before, so I'm very embarrassed because it didn't work after the cloud transfer. I'm inquiring because I haven't made any progress … -
Stripe Subscription Update with Django and React
I have developed backend implementation for Stripe API calls to handle the following requests : urlpatterns = [ path('subscription', SubscriptionCreate.as_view(), name="create_subscription"), path('add_payment_method', PaymentIntentCreate.as_view(), name="add_payment_method"), path('delete_payment_method', PaymentIntentDelete.as_view(), name="add_payment_method"), path('customer', CustomerView.as_view(), name="customerview"), path('webhook', stripe_webhook, name="stripe_webhook") ] Here below are my models in Django backend to handle information regarding products and the customer : class Product(models.Model): class Plan(models.IntegerChoices): FREE = 0, _('Free') BASIC = 1, _('Basic') PREMIUM = 2, _('Premium') ENTENPRISE = 3, _('Enterprise') plan = models.PositiveSmallIntegerField(choices=Plan.choices, null=False, blank=False, default=Plan.FREE) stripe_plan_id = models.CharField(max_length=40) class Customer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40, default="") product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) stripe_subscription_id = models.CharField(max_length=40, default="") clientsecret = models.CharField(max_length=80, default="") active = models.BooleanField(default=True) Also I have a post_save function that is triggered by "User Creation in Django" which also creates a Stripe Customer associated with each user and a subscription with a FREE plan that does not require payment / card information : post_save.connect(post_save_customer_create, sender=settings.AUTH_USER_MODEL) stripe_subscription = stripe.Subscription.create( customer=customer.stripe_customer_id, items=[{"price": customer.product.stripe_plan_id},], payment_behavior='default_incomplete', payment_settings={'save_default_payment_method': 'on_subscription'}, expand=['latest_invoice.payment_intent'], ) However, when the user wants to upgrade their subscription from Free to Paid models (Basic, Premium, Enterprise) then payment method / card information is required. In this case I want the subscription get into a "Incomplete" state until the payment is …