Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to present Pandas Contingency Table in Django Template? How to iterate to get rows?
how can I get Pandas Contingency Table to Django Template? First I created function which returns contingency table with data from model: def monthly_quantity_table(table): mtable = pd.pivot_table(table, index="name", columns="link", values="quantity", aggfunc=np.sum, margins=True, fill_value=0, margins_name="TOTAL") return mtable Second I created necessary View to be able to get context to template: class StatsCategoryView(LoginRequiredMixin, FilterView): template_name = "stats/stats_category.html" model = SalesData filterset_class = StatsCategoryFilter ... def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) entry_data = self.object_list.values().order_by("date") ... try: mtable = utils.monthly_quantity_table(table) except: mtable = [0, 0, 0, 0] context["c1_m_table"] = mtable return context And finally I tried to present data from contingency table in template: First I checked that there is data and it is working. And it is OK, I can see data in template, function and view is working, but there is no formatting to rows or columns: <div class="row"> <div class="col"> {{ c1_m_table }} </div> </div> But then I tried iterate by rows from table, but it is not working and I am getting no data: <div class="row"> <div class="col"> {% for index, row in c1_m_table.iterrow %} {{ row }}<br> {% endfor %} </div> </div> I would like to iterrate through contingency table to get particular rows and to format them to … -
replace the base editor in django-wiki app
I use django-wiki app : https://django-wiki.readthedocs.io/en/main/ I try to replace the base editor. The default param are : wiki.conf.settings.EDITOR = 'wiki.editors.markitup.MarkItUp' I installed Martor (Markdown Editor plugin for Django) : https://github.com/agusmakmun/django-markdown-editor I don't know how properly load it. I tried import martor wiki.conf.settings.EDITOR = 'martor' and catch this error : django.core.exceptions.ViewDoesNotExist: '<module 'martor' from '/home/gabriel/Dev/Web/Projets/wp_ahimawiki/venv/lib/python3.10/site-packages/martor/init.py'>' is not a callable or a dot-notation path I tried also many things and catch differents errors. How properly change the django-wiki editors config ? Thanks for reading. ps: I use the last version of all packages (in a virtualenv) Linux Mint 21 Python 3.10.4 django 4.0.7 Markdown==3.3.7 martor==1.6.14 wiki==0.9 -
Unable to load min.js and min.css files in Django when debug=False
I am trying to deploy my website to Heroku for that I made some changes in the setting file. After that, I'm unable to runserver in debug=False. I got some issues with .min.js and .min.css file. I am getting the following error after running the server in debug=False (Djangoenv) PS E:\Engineering\Programming\Django\projects\Portfolio\New Instance 18-9\CRRathod> python manage.py runserver Performing system checks... System check identified no issues (0 silenced). September 18, 2022 - 16:32:16 Django version 4.0.6, using settings 'crrathod.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Traceback (most recent call last): File "c:\users\lonar\appdata\local\programs\python\python38\lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\wsgi.py", line 132, in __call__ response = self.get_response(request) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\base.py", line 140, in get_response response = self._middleware_chain(request) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner response = response_for_exception(request, exc) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 139, in response_for_exception response = handle_uncaught_exception( File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\whitenoise\middleware.py", line 60, in __call__ response = self.get_response(request) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 57, in inner response = response_for_exception(request, exc) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 139, in response_for_exception response = handle_uncaught_exception( File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\utils\deprecation.py", line 134, in __call__ response = response or self.get_response(request) File "E:\Engineering\Programming\Django\Djangoenv\lib\site-packages\django\core\handlers\exception.py", line 57, … -
Django PermissionRequiredMixin not working
When I place the PermissionRequiredMixin as the most left paramenter, my requests get forwarded to the login URL even though the request is coming from an already authenticated user. class ExampleViewSet(PermissionRequiredMixin, viewsets.ModelViewSet): permission_required = ('example.example_view',) When I place the PermissionRequiredMixin after the ModelViewSet the authenticated user is detected, however, the permission_required is ignored, and every user without the permission is allowed as well. And this answer suggested, that this is caused by the placement of the parameter, which leads to the first problem. class ExampleViewSet(viewsets.ModelViewSet, PermissionRequiredMixin): permission_required = ('example.example_view',) How do I solve this problem? -
name 'message' is not defined in django python
@login_required(login_url='login_user') def hrmanager(request): template = 'Job_portal/job_listing.html' if request.method == 'POST': form = job_posting_form(request.POST, request.FILES) if form.is_valid(): form.save() message.success(request, 'Job Posted Successfully') return redirect('hrmanager') job_posting = Job_posting_hr.objects.all() user = "hrmanager" job_add_form = job_posting_form() context = { 'edit_form': job_add_form, 'user': user, 'job_posting': job_posting } return render(request, template, context) -
Django - django.core.exceptions.FieldDoesNotExist - has no field named
On our production server we got the following error when restarting django or try to run 'python manage.py makemigrations' django.core.exceptions.FieldDoesNotExist: pricing.pricing has no field named 'price_per_hour' What is strange is that the field price_per_hour was renamed long time ago to price and the migration when well. But now I got this error every time and it is preventing to make any other model modification (in any app) and migrations. What I checked : If I run 'python manage.py showmigrations' every migration is flagged with an X, which if I'm right, means all the migration were done price_per_hour is no longer find/used in any of the django app / class class Pricing(models.Model): price = models.DecimalField(default=5,max_digits=10, decimal_places=2) class Meta: ordering = ['-price',] def __str__(self): return "{}".format(self.price) I also exported the matching./current database in sql and we well see that it contains price column and not price_per_hour. And no reference anywhere to price_per_hour CREATE TABLE public.pricing_pricing ( id integer NOT NULL, price numeric(10,2) NOT NULL, ); I also tried to rename the filed price to price_per_hour just in case but it didn't help For me it seems the error comes from Django rather than the postgrsql database but I'm no sure. I don't … -
pg_restore: error: input file is too short (read 0, expected 5)
I have a backup of PostgreSQL database(taken from Heroku) now I want to restore this backup to my local database but it's not working. tried from CMD and pgadmin, but no luck! what wrong I am doing? pg_restore --verbose --clean --no-acl --no-owner -h localhost -U nafuser -d naf latest.dump pgadmin issue -
Slant on divs from css border?
Here is my html: <div style="margin: 0 auto; margin-top: 25px; text-align: center; padding: 0px;"> {% for name in client_name %} <div class="appointment_data_div">{{ name }}<div> {% endfor %} </div> css: .appointment_data_div { margin: 0 auto; margin-top: 50px; width: 600px; height: 50px; box-shadow: 0px 5px 5px 0 #cccccc; border-radius: 15px; padding-top: 10px; border: 2px solid black; } For some reason, as you can see below, the divs are slanted?? I'm using django as my framework. -
Django deployment with apache server error
I have a django application deployed on apache server. following is os and apache details: Server Version: Apache/2.4.41 (Ubuntu) OpenSSL/1.1.1f mod_wsgi/4.6.8 Python/3.8 when restarting apache and trying to access website i have this error: /var/www/backend/venv2/lib/python3.8/site-packages/pandas/__init__.py:11: UserWarning: NumPy was imported from a Python sub-interpreter but NumPy does not properly support sub-interpreters. This will likely work for most users but might cause hard to track down issues or subtle bugs. A common user of the rare sub-interpreter feature is wsgi which also allows single-interpreter mode. [wsgi:error] Improvements in the case of bugs are welcome, but is not on the NumPy roadmap, and full support may require significant effort to achieve. .... [wsgi:error] raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") [wsgi:error] django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. as you can see first it gives me a warning about numpy and after it, it gives me error about SECRET_KEY which supposed to read it from environment variables. SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') for this issue i read couple of texts and other stackoverflow questions and i even tried following directive inside my apache config file. WSGIApplicationGroup %{GLOBAL} but still nothing. -
Customize model manager in django
I am working on a django blog project. this is my models.py code: from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class PublishManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Post.Status.PUBLISHED) class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="blog_posts") title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2,choices=Status.choices,default=Status.DRAFT) objects = models.Manager() published = PublishManager() class Meta: ordering = ['-publish'] indexes = [ models.Index(fields=['-publish']) ] def __str__(self): return self.title when i put “published = PublishManager()“ on top of “objects = models.Manager()” like this: published = PublishManager() objects = models.Manager() i found that my admin site didnt show the entry with draft status. if i create a Post object with status equal Published,then it will be show in my admin site.if i create an object with status Draft,it won't show in admin site. i don't know why,could anyone can help me? -
Django Cart Total
I am making an e-commerce site with django. I set it to pay with paypal. But my problem is that I can't set the cart total when you pay. Here is the html code: ... createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value:'{{value}}' } }] }); }, ... Here is the models.py class Product(models.Model): name = models.CharField(max_length=200) image = models.ImageField(upload_to='images/') value = models.IntegerField(null=True) def __str__(self): return self.name class Order(models.Model): username = models.CharField(max_length=200,null=True) name = models.CharField(max_length=200) value = models.IntegerField(null=True) image = models.ImageField(upload_to='images1/',null=True) def __str__(self): return self.name Here is the views.py: #Make an order if request.method == 'POST': name = request.POST['name'] product = Product.objects.filter(name=name).first() value = int(product.value) order = Order(name=name,username=cookie,value=value,image=product.image) order.save() #Buy def buy(request): cookie = request.COOKIES.get('name') if not cookie: return redirect('/') orders = Order.objects.filter(username=cookie).all() for i in orders: global value value = int(i.value) value = value + value return render(request,'cart.html',{'orders':orders,'value':value}) But I don't get the right value. How can I count the total value? Thanks. -
Django channels - why can't I receive data from js in websocket_disconnect method?
I have a chat application and I want to implement a feature that makes all messages read when a certain user disconnects from an active chat. I can get the user with self.scope['user'] but I don't know how to get the active chat from chatroom.js. My code: consumers.py class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) ... async def websocket_receive(self, event): print('receive', event) ... async def websocket_disconnect(self, event): print('disconnect', event) received_data = json.loads(event['text']) user = self.scope['user'] chat_id = received_data.get('chat_id') chat_obj = await self.get_thread(chat_id) await self.disconnect_update_read_status(chat_obj, user) chatroom.js let loc = window.location let wsStart = 'ws://' if(loc.protocol === 'https') { wsStart = 'wss://' } let endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) socket.onopen = async function(e){ console.log('open', e) ... } socket.onmessage = async function(e){ console.log('message', e) ... } socket.onerror = async function(e){ console.log('error', e) } socket.onclose = async function(e){ console.log('close', e) let thread_id = get_active_thread_id() let data = { 'chat_id': thread_id } data = JSON.stringify(data) socket.send(data) } I tried this solution but I had an error, when disconnecting websocket didn't receive data: disconnect {'type': 'websocket.disconnect', 'code': 1001} WebSocket DISCONNECT /chat/ [172.20.0.1:54750] Exception inside application: 'text' Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ … -
Django Product price calculation
Here I am having a product detail. ```class product(models.Model): Product_name = models.CharField(max_length=50, null=True) product_description = models.TextField(max_length=170, null=True) product_price = models.SmallIntegerField(null=True) def __str__(self): return self.Product_name``` Depending on the product selection the value "30" has to change dynamically pending on the product. So that It will calculate price automatically. Please help me. user = form.save(commit=False) products = form.cleaned_data['Product'] Quantity = form.cleaned_data['Quantity'] shoping_product = product.objects.filter(Product_name= products) sub_total = 30 * Quantity user.Gst = 30 * (1 + 0.18) user.Price = sub_total + user.Gst user.save() messages.success(request, 'Registration successful.') return redirect('home')``` -
Django Error : ValueError at / Field 'ticket_id' expected a number but got 'NS000001'
While Inserting data, I got this error. May be this could be due to change of default primary key. I do not want to enter ticket_id field as I have set default value for that field (default='NS000001') models.py class Ticket(models.Model): ticket_id = models.AutoField(primary_key=True, default='NS000001', editable=False) server_details = models.CharField(max_length=100) send_date = models.DateTimeField(default=timezone.now) license_no = models.CharField(max_length=25) file = models.FileField(upload_to='documents/%Y/%m/%d/') def __str__(self): return self.ticket_id views.py def Index(request): if request.method == "POST": form = SaveTicket(request.POST,request.FILES or None) if form.is_valid(): form.save() print(form) return redirect('index') else: form = SaveTicket() return render(request, 'index.html') forms.py class SaveTicket(forms.ModelForm): class Meta: model = Ticket fields = ['server_details','send_date','license_no','file'] -
How can I send csrf_token?
Good afternoon! Please help me send csrf_token to the POST function for an authorized user. The error is, when I do user registration, the Forbidden (CSRF token missing.) error comes out: /data/task. The link to the library is below (there is also a demo project for this link). https://docs.dhtmlx.com/gantt/desktop__howtostart_python.html -
Not able to perform update and delete operation using custom html input fields
I am a beginner to Django. I am now doing a small project and I am encounter an issue while doing the update and delete operation. I am using forms.py but using custom input fields in html file. I have tried many ways but it returns errors. When I try to update it creates a new entry instead of update. When I perform delete nothing happens. Please go through the below code and help me out to resolve this. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('contacts', views.contacts, name='contacts'), path('update/', views.update, name='update'), path('delete/', views.delete, name='delete'), ] views.py def update(request, contact_id): details = Contact.objects.filter(id=contact_id) if request.method == 'POST': form = ContactForm(request.POST or None, instance=details) if form.is_valid(): form.save() return redirect('contacts') else: return render(request, 'update.html', {'details':details}) def delete(request, contact_id): contact = Contact.objects.all() if request.method == 'POST': details = Contact.objects.get(id=contact_id) details.delete() return redirect('contacts') return render(request, 'contacts.html', {'contact':contact}) contacts.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>Document</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="row mt-5"> <div class="col-sm-8"> <a href="{% url 'home' %}" class="btn btn-primary mb-3">Home ></a> <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> … -
How to optimize django admin sql query of a field in list display
My code is class MetricAdmin(admin.ModelAdmin): list_filter = ('customer',) exclude = ('unavailable_clients','metric_group') form = MetricForm action_form = TriggerBackfillMetricForm actions = ["trigger_backfill_metric"] list_display = ('parameter_name',) i only want parameter name in my list display but underlying query fetching all the fields. I am using postgres as my database. I have little idea about how to override the get_queryset method Executed SQL SELECT "devices_physicalparameter"."id", "devices_physicalparameter"."parameter_name", "devices_physicalparameter"."parameter_type", "devices_physicalparameter"."query_name", "devices_physicalparameter"."display_name", "devices_physicalparameter"."display_unit_id", "devices_physicalparameter"."multiplier", "devices_physicalparameter"."operator_choice", "devices_physicalparameter"."filter_operator_id", "devices_physicalparameter"."parameter_properties", "retail_metric_basemetric"."physicalparameter_ptr_id", "retail_metric_basemetric"."customer_id", "retail_metric_basemetric"."enabled", "retail_metric_basemetric"."display_name_filter", "retail_metric_basemetric"."all_sites_required", "retail_metric_basemetric"."rate", "retail_metric_basemetric"."include_pseudometers", "retail_metric_basemetric"."batch_size", "retail_metric_basemetric"."time_shift_start", "retail_metric_basemetric"."time_shift_stop", "retail_metric_basemetric"."publish_when_all_controllers_available", "retail_metric_basemetric"."metric_group", "retail_metric_basemetric"."level", "retail_metric_basemetric"."type", "retail_metric_dcmeterenergymetric"."basemetric_ptr_id", "retail_metric_dcmeterenergymetric"."day_start_time", "retail_metric_dcmeterenergymetric"."day_end_time", "retail_metric_dcmeterenergymetric"."calculation_mode" FROM "retail_metric_dcmeterenergymetric" INNER JOIN "retail_metric_basemetric" ON ("retail_metric_dcmeterenergymetric"."basemetric_ptr_id" = "retail_metric_basemetric"."physicalparameter_ptr_id") INNER JOIN "devices_physicalparameter" ON ("retail_metric_basemetric"."physicalparameter_ptr_id" = "devices_physicalparameter"."id") ORDER BY "devices_physicalparameter"."parameter_name" ASC how can i optimize it so it only fetch the field i want. -
Allowing tabs doesn't work in regex (Python)
I have this regex: text_reg = _lazy_re_compile(r"^[A-Za-z0-9\t#&@$()_+=':%/\",.!?*~`\[\]{}<>^;\\|-]+$") \t should be enough, right? This seems to be working on regex101, however somehow it does not work in my script. def validate_text(value, exctype=ValidationError): if len(value.strip()) < 1: raise exctype(_("empty")) if text_reg.fullmatch("".join(value.splitlines())) is None: args, kwargs = [_("not allowed.")], {} if exctype == ValidationError: kwargs["params"] = {"value": value} raise exctype(*args, **kwargs) What am I missing? -
Django 4.1.1 ChoiceField widget=forms.RadioSelect label tag missing 'for' attribute
I just upgraded from django 2.0.2 to 4.1.1. I have a few form fields of type ChoiceField with forms.RadioSelect. In django 2.0.2 the tag included a 'for' attribute/id so I can query in the template {% if field.id_for_label == "xyz" %}. However in 4.1.1 the 'for' attribute/id is not included (when inspecting the html source generated), so field.id_for_label is empty. All other fields labels still include 'for' attributes/id. Questions: Has anyone seen this problem? Is there a way to 'force' a 'for' attribute on the labels? Is there some other way to identify a field? I tried ... {% if field.label_tag == "label text" %}, but no good. Thanks, Doug -
How do I pass the value from the inside of a for loop ( jinja2 ) to a bootstrap modal to display it in side the modal body?
How do I pass the value from the inside of a for loop ( jinja2 ) to a bootstrap modal to display it in side the modal body? here is my views.py file: if request.method == 'GET': driver = get_network_driver(device.napalm_driver) with driver(device.IP_address, device.username, device.password) as device_conn: interfaces = device_conn.get_interfaces() context = { 'device': device, 'interfaces': interfaces, } return render(request, 'network/interface_list.html', context) Please note that the the device_conn.get_interfaces() method returns a nested dictionary. Here is the html template: {% extends 'base/base.html' %} {% block title %}iNet Interface List{% endblock %} {% block content %} <div class="section"> {% include 'network/include/interface_list_header.html' %} {% if messages %} {% for message in messages %} {% if message.tags == 'success' %}<div class="alert alert-success" role="alert"> {{ message }} </div>{% elif message.tags == 'error' %}<div class="alert alert-danger" role="alert"> {{ message }} </div>{% endif %} {% endfor %} {% endif %} <div class="card mx-auto shadow rounded"> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <th scope="col" style="text-align:center">Interface Name</th> <th scope="col" style="text-align:center">Admin status</th> <th scope="col" style="text-align:center">Protocol</th> <th scope="col" style="text-align:center">Description</th> <th scope="col" style="text-align:center">MAC Address</th> <th scope="col" style="text-align:center">Last Flapped</th> <th scope="col" style="text-align:center">Turn On/Off Port</th> <th scope="col" style="text-align:center">Edit Description</th> </tr> </thead> <tbody> {% for interface_name, interface in interfaces.items %} <tr> <form action="{% … -
How does Django offer code completion for Query.filter method?
If I have a Django model like: class Example(models.Model): is_in_stackoverflow = models.BooleanField() and I try to filter said model like: Example.objects.filter(is_in_stackoverflow=True) My IDE (Pycharm to be specific) knows to offer me other kwargs based on the fields I specific for my model (for this case it might offer me is_in_stackoverlow__in or is_in_stackoverlow__isnull) I would like to replicate this functionality in a library I am writing. I tried looking into the django source code but was unable to figure this magic out. -
Sorting sizes with two or more numbers in Django
I am trying to sort items that have sizes described by two numbers like the following 10 x 13 100 x 60 7 x 8 The size is saved as a string. I want them sorted like this 7 x 8 10 x 13 100 x 60 how can this be achieved with Django? -
How to filter Many to Many field in django admin page using a foreign key value?
I am trying to filter my many to many variation fields with respect to the product. means I only want the variations related to the product to show in the admin. now its showing all the variations available for every product. I added formfield_for_manytomany() function to my admin.py but how can I get the current product(id) in the cart or order to filter the variations? It may be simple, but I am new in this field! admin.py from django.contrib import admin from .models import * from products.models import Variation class CartAdmin(admin.ModelAdmin): list_display = ('cart_id', 'date_created') class CartItemAdmin(admin.ModelAdmin): list_display = ('user','cart', 'product', 'quantity','is_active') def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "variation": product = Products.objects.get(id='??') # how I get the current product in the cart or order kwargs["queryset"] = Variation.objects.filter(product=product.id) return super().formfield_for_manytomany(db_field, request, **kwargs) admin.site.register(Cart, CartAdmin) admin.site.register(CartItem, CartItemAdmin) CartItem Model class CartItem(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True) product = models.ForeignKey(Products, on_delete=models.CASCADE) variation = models.ManyToManyField(Variation, blank=True) quantity = models.IntegerField() is_active = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) def item_total(self): return self.product.price * self.quantity def __str__(self): return self.product.name Product and Variation Model class Products(models.Model): name = models.CharField(max_length=50, unique=True) slug = AutoSlugField(populate_from='name', max_length=100, unique=True) isbn = models.CharField(max_length=20, unique=True, blank=True, null=True) sub_category … -
Requests_HTML getting Error "There is no current event loop in thread Thread-3" - Python
I am trying to load javascript and parse this website. I have the code below that, based on what I have come across, should work. I keep getting the following error message when I compile however. There is no current event loop in thread 'Thread-3' I am really new to Requests-HTML and don't understand what this could be due to. I have been doing some research but everything doesn't seem very relevant to what I am doing and everything seems to be using something called "async". How do I fix this error? Thanks in advance! import requests from bs4 import BeautifulSoup google_initiate(request) def google_initiate(request): form = SearchForm(request.POST or None) if form.is_valid(): url = 'https://www.google.com/search?biw=1866&bih=1043&tbm=shop&q=desk&tbs=mr:1,price:1,ppr_min:,ppr_max:,avg_rating:None' session = HTMLSession() response = session.get(url) response.html.render() print(response.html) google_parsed = response.html.find('.sh-dgr__gr-auto.sh-dgr__grid-result') response.close() session.close() return google_parsed -
Django in Heroku
Hola intento utilizar aplicacion django con BD postgres en Heroku y tengo este error Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.9/site-packages/psycopg2/init.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in init self.build_graph() File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/loader.py", line 216, in build_graph …