Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No 'Access-Control-Allow-Origin' header is present on the requested resource. - Django & React
I have a ReactJS & Django application. I have a cors issue that I try to solve with Django cors header. However, when I try to add localhost:3000 to my whitelist, I receive a cors error claiming: Access to fetch at 'http://localhost:8000/api/register' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. However, when I click on submit, my user still registers successfully. I also notice when I replace CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000", "http://localhost:8000", ] to CORS_ORIGIN_ALLOW_ALL = True my cors issue is solved. Is there's something that I am doing wrong? I am not trying to exempt my cors. I can pass the CSRFToken successfully from react to Django. Please take a look at the images below to get a better understanding of what I am doing. -
How to obtain a list of scheduled Django-Q tasks from a Django View
All, I've implemented Django-Q and Redis and it works great if I use Django Admin to manage everything. Now I'm ready to reproduce the functionality that Django Admin provides from within my app. I'm able manage a schedule tasks but I can't figure out how to obtain a list of what's been scheduled as well as what has successfully ran and failed. Any thoughts on how I can access a list of what's been scheduled? -
Django Bootstrap Carousel 4 items at a time
Good day SO. I want to use Bootstrap Carousel with Django and display 4 items per carousel-item. (With a maximum of 20 items) First on my views, I have created a view: items = AllItems.objects.all().order_by('-id') context['items'] = items Next, on my template I believe I need to loop through my items like this <div class="carousel-inner"> {% for item in items%} {% if forloop.counter|divisibleby:4 == 1 or forloop.first %} // Add the opening div <div class="carousel-item"> {% endif %} <div class="item">{{item.item_title}}</div> // Add the items {% if forloop.counter|divisibleby:4 == 0 or forloop.last %} // Add the closing div </div> {% endif %} {% endfor %} </div> But reality is different. Hoping to ask your logic on this type of scenario. -
How to insert Django data on Nginx logs?
Im thinking on retrieve Django user data on the user authetication class and pass it to Nginx session variables, then on the nginx logging settings use that data to create a Nginx log that contains the Django user that create such a request. I have found these ideas: Get current request by Django's or Python threading https://gist.github.com/vparitskiy/71bb97b4fd2c3fbd6d6db81546622346 https://nedbatchelder.com/blog/201008/global_django_requests.html Set a session variable: How can I set and get session variable in django? And then log the cookie variable via a Nginx configuration like: https://serverfault.com/questions/223584/how-to-add-recently-set-cookies-to-nginxs-access-log https://serverfault.com/questions/872375/what-is-the-difference-between-http-cookie-and-cookie-name-in-nginx Any better idea?. I'm reinventing the wheel? -
Problem with ImageField in ModelForm Django, request.FILES empty
I have a problem with django working with FormView, and forms.ImageField This is my models.py class Product(models.Model): [...] image = models.ImageField( 'Imagen', upload_to='Productos', ) price = models.IntegerField('Precio del metro cuadrado') content = models.ForeignKey(Content, on_delete=models.CASCADE) objects = ProductManager() class Meta: verbose_name = ("Producto") verbose_name_plural = ("Productos") def __str__(self): return self.product_name forms.py class ProductForm(forms.ModelForm): [...] form_type = forms.CharField( required=False, widget=forms.HiddenInput() ) image = forms.ImageField() class Meta: model = Product fields = ( 'product_name', 'subtitle', 'price', 'description', 'image', 'form_type', ) def clean(self): cleaned_data = super(ProductForm, self).clean() product_name = self.cleaned_data.get('product_name') form_type = self.cleaned_data.get('form_type') products = Product.objects.all() for p in products: if p.product_name == product_name and form_type != 'Update': self.add_error('product_name', 'El nombre de este producto ya existe') return self.cleaned_data My views.py class ProductCreateView(LoginRequiredMixin, FormView): form_class = ProductForm template_name = 'producto/product-form.html' success_url = reverse_lazy('product_app:product-list') login_url = reverse_lazy('usuario_app:login') def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) print(request.FILES) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): print('Entra') response = super(ProductCreateView, self).form_valid(form) response.delete_cookie('error') return response This is my html with enctype="multipart/form-data" <form action="{% if product == None %}{% url 'producto_app:product-create' %}{% else %}{% url 'producto_app:product-update' product.product_id %}{% endif %}" id="productForm" method="POST" enctype="multipart/form-data" > <div class="modal-body"> {% csrf_token %} <div class="form-group"> <label for="product_name"> <span class="text-danger">*</span> Nombre del … -
Django - Iteration in two lists of multiple values returning only one set of iteration
I have an issue in relation to zip() and iteration. nutritional_info_quantity_per_user = [] if related_profiles: for r in related_profiles: r_perc = round((r.kcal/self.request.user.profile.kcaltotal)*100) for intake in intakes: intake_quantity = intake.amount intake_custom_quantity_per_user = myround_two((intake_quantity/menu_kcal) * (kcal)*(r_perc/100)) nutritional_info_quantity_per_user.append(intake_custom_quantity_per_user) (...) nutritional_infos_per_user = zip(intakes, nutritional_info_quantity_per_user) (...) Queries are good as they are returning the full list of values. But when I loop through "nutritional_infos_per_user" in the template as follows: {% for t, i in nutritional_infos_per_user %} {{t.type.name}} {{i}} {% endfor%} I only get the first iteration (however I have two or more "related_profiles"). Clearly I am doing something wrong and I would be very grateful if someone could help ! Many thanks. -
Using django_property_filter but PropertyChoiceFilter failing to match on Inactive
I can't figure out what I'm doing wrong here. I'm using django_property_filter to add a filter to my list of employees. I have an Employee model to extend the User model. It has a property of is_active to return the user model's is_active value. class Employee(models.Model): """Model representing an employee - one-to-one with user""" user = models.OneToOneField(User, on_delete=models.CASCADE) @property def is_active(self): """Property to return active status of user to employee model""" return self.user.is_active I have a propertyfilter using django_property_filter class EmployeeFilter(PropertyFilterSet): ACTIVE_CHOICES = ( (True, 'Active'), (False, 'Inactive'), ) active = PropertyChoiceFilter(choices=ACTIVE_CHOICES,field_name='is_active',lookup_expr='exact',label='Active') class Meta: model = Employee fields = ['locations'] I'm using a function based view to list all employees. def EmployeesList(request): employee=getemployeefromuser(request) if employee: emp_list = Employee.objects.filter(hotel__exact=employee.hotel).order_by('user') f = EmployeeFilter(request.GET, queryset=emp_list) emp_list = f.qs paginator = Paginator(emp_list, 20) page = request.GET.get('page', 1) try: emps = paginator.page(page) except PageNotAnInteger: emps = paginator.page(1) except EmptyPage: emps = paginator.page(paginator.num_pages) context = { 'filter':f, 'emps':emps, } return render(request, 'staffapp/employee_list.html', context=context) The filters display as expected. The location filter works correctly. The active filter works correctly for ----/None and Active/True but when I select Inactive it just returns the same results as Active. The URL correctly appends "?Active=False" but the resulting employee records are … -
Using Django urls and Vue routes in the same project
I'm creating a Django app and i already made the whole authentication layer using Django templates and Django urls, in order to handle authentication i used django-allauth. Since the app requires a lot of interactivity and heavy use of real time features, i realized i need to use VueJS and i already have some Vue components ready. The big problem is that if i add Vue and turn my application in a SPA, i'm going to have to rewrite this whole authentication layer from Vue, which is quite difficult and not exactly my field, so would it be possible to have the authentication part handled by Django urls and Django templates rendered by standard Django views and the rest of the app as a Vue SPA that uses Vue routes? So basically i have: from django.urls import path, include from . import views from .views import SignUpView urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), path('login/', LoginView.as_view(), name='login'), ... path('', views.index, name='index') ] After logging in from a template rendered by a django view, the user is redirected to the Vue app, where urls are handled by Vue routes. What happens if i do this? If the route is handled by Vue, … -
How to preserve whitespace in a create form in django
I just wanted to know how to preserve whitespace while creating forms in Django. So if I had a create form, and i just created a post on my site, the whitespace needs to be preserved. for example. text text the space in the middle is what i want preserved. But for now, it just groups them. text text it returns that. So please let me know how. forms.py class AnnouncementsSectionCreateForm(forms.ModelForm): is_pin = forms.BooleanField(label="pin announcement post", required=False) class Meta: model = AnnouncementsSection fields = ('title', 'description', 'is_pin') widgets = { 'title': forms.TextInput(attrs={ 'class': 'form-control' }), 'description': forms.Textarea(attrs={ 'class': 'form-control', }), } so my model, views, and my template don't seem to be important for this. I am pretty sure, all the work is in forms.py. So please let me know how. Thanks! -
How to change design of a form in template? Django
I am trying to customize my form design and there are some things I dont know how to delete/ change. forms.py class UserProfileAvatarForm(forms.ModelForm): class Meta: model = Profile fields = ['avatar'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['avatar'].widget.attrs.update( {'class': 'form-control', 'type': 'file', 'id': 'formFile'}) This is what I get: How can I get rid of "Currently" and "Change:"? This is the html output: I can give display:none to a tag to make it disappear, but "Currently" and "Change:" dont have a tag. Is there any solution? It has to do with css or with forms.py? -
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?: Heroku/Django
I've been struggling over this for days now and none of the numerous threads I've come across have worked for me. I have a Postgresql DB with postgis extention that I access with pgadmin4 for my Django app. I semi-successfully deployed my application to Heroku, except anything that needs data from the psql DB does not work, I get the error mentioned in the title. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'geospatial': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geospatial', 'USER': '****', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT': '5432', } } error: OperationalError at /facility/ could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Request Method: GET Request URL: http://lessmedtxt.herokuapp.com/facility/ Django Version: 3.1.5 Exception Type: OperationalError Exception Value: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? adding the below code to my settings.py does nothing either: import dj_database_url geodbtest = dj_database_url.config() DATABASES['geospatial'].update(geodbtest) DATABASES['geospatial']['ENGINE'] = 'django.contrib.gis.db.backends.postgis' django_heroku.settings(locals()) I've run heroku run python manage.py migrate but it says I have no migrations to apply. Please help me, I've spent days over trying … -
Django templates - request in url problem
I've got a quite a problem with solving some {% url %} issue in django. Im currently creating small e-commerce website where you can check other people's profiles. Im currently using navbar which is included in every template via {% inclue 'navbar.html' %}. Here is the most important fragment of it: Navbar.html {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'view_profile' username=request.user.username %}">My Profile</a> </li> {% endif %} </ul> </div> {% if user.is_authenticated %} <a href="account_settings.html"><span class="hello-msg">Hello, {{request.user.first_name}}</span></a> <a href="{% url 'logout' %}"><span class="hello-msg">Logout</span></a> {% else %} <a href="{% url 'login' %}"><span class="hello-msg">Login</span></a> <a href="{% url 'register' %}"><span class="hello-msg">Sign up</span></a> {% endif %} Everywhere except "view_profile" view, it works as intended. When I'm logged off I don't see "my profie" href or "logout" href etc. But the problem is appearing when I try to enter view_profile path without being logged in. Even though I'm checking if user is logged in Navbar.html {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{% url 'view_profile' username=request.user.username %}">My Profile</a> </li> {% endif %} It gives me: Keep in mind, this problem doesnt appear ANYWHERE (navbar is in all templates) except profile view, even though the link is correct and is providing username, … -
django heroku build can't find config vars
I have a staging app which is deployed but have some disturbing logs when trying to import the config vars from heroku. Here is a sample: -----> Exporting application config values -----> Loading environment information cat: /tmp/d20210317-55-vc7xqe//tmp/d20210317-55-vc7xqe/ALLOWED_HOSTS: No such file or directory /tmp/codon/tmp/buildpacks/9f6bae6fc2432740f5d76d23e8fbcb5e7b35afaa/bin/compile: line 11: export: `/tmp/d20210317-55-vc7xqe/ALLOWED_HOSTS=': not a valid identifier cat: /tmp/d20210317-55-vc7xqe//tmp/d20210317-55-vc7xqe/COMPRESS_ENABLED: No such file or directory any idea why this is happening? -
Django Model Validation. How would I check to see if the users inputs match a Users in the database table
// Model class that displays the fields for the different models class Users(models.Model): // Possible department choices departmentChoices = ( ('MD', 'Math department'), ('ED', 'English department'), ('HD', 'History department'), ('GD', 'Geography department'), ('FD', 'Finance department'), ) username = models.CharField(max_length=20) password = models.CharField(max_length=25) department = models.CharField(max_length=23, choices=departmentChoices, primary_key=True) // views login function def login(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] department = request.POST["department"] user = auth.authenticate(username=username, password=password, department=department) if user is not None: auth.login(request, Users) # return the home page as the login was succesfull return redirect("home.html") # User doesnt exists return render(request, 'login.html') //return the login page again if the users login details don't match a record from the models database table -
Does Django allow you to take in user input and run it through a custom method?
I am fairly new to Django and am attempting to build a web application in which I can ask for user input and run it through a method. I used twint and wrote some code that allows a user to input either a stock ticker or a username within a date range and it will pop out all the tweets that either contain either the ticker or the username. Being that I am still new at Django (I've built a basic blog following a tutorial and that's about it), I was wondering if 1) it was possible to build what is described above and 2) suggestions on where to start. Thank you -
Issues with printing bytea data from PostgreSQL in python, but always get <memory at 0x> address
So I am having some troubles getting access the bytea binary data from PostgreSQL using Python. So this is the model for Images: class Images(models.Model): image_code = models.BinaryField() caption = models.CharField(max_length=100,default='IMG_CAPTION') Here is the data table from PostgreSQL | id |image_code (bytea) | caption (char var) | | ---|---------- | ------- | | 1|[binary] | DEFAULT CAPTION | So in my project I have following store_length = len(Images.objects.all()) image_shown = Images.objects.all()[store_length-1] code_string = image_shown.image_code print(code_string.image_code) The output I get is memory address <memory at 0x7ff5ae03a888>. The output is supposed to be string. What should I do here? -
Django 2.2 Upgrade + TransactionManagement Error + During Tests execution
We are upgrading the django application from version 1.11 to version 2.2 and we have almost done the necessary upgrade, and when we are running the testcases, we are getting error as django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. and we are able to run the same testcases in django 1.11. Even When I run below simple testcase with django 2.2 version is also giving error as mentioned above and its not even printing "hello" statement from setup method. libraries we are using pytest 4.4, pytest-django-3.4.5 and django 2.2 and djangorestframework 3.11 I have done more research, but could not able to find solution, please advise from django.test import TestCase class GetValuesTestCase(TestCase): def setUp(self): print("hello") def test_hello(self): print("hhh") -
PATCH request for myown user object returns a 405 code
so im trying to make a url like some_site/me/, that shows my profile and the patch for some reason doesnt work heres a view: class MyUserViewSet(viewsets.ModelViewSet): pagination_class = None permission_classes = [permissions.IsAuthenticated] serializer_class = UserSerializer def get_queryset(self): return User.objects.filter(username=self.request.user.username) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset[0]) return Response(serializer.data) def partial_update(self, request, *args, **kwargs): queryset = self.list() serializer = UserSerializer(queryset, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() a serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = 'first_name', 'last_name', 'username', 'bio', 'email', 'role' lookup_field = 'username' a model if needed class User(AbstractUser): USER_ROLE = ( ('user', 'user'), ('moderator', 'moderator'), ('admin', 'admin'), ) role = models.CharField(max_length=9, choices=USER_ROLE, default='user') email = models.EmailField('email address', unique=True) bio = models.TextField(max_length=300, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['role',] my guess is smths up with the retrieve thing -
How to parse the queryset from django-simple-history?
How to parse the queryset from the django-simple-history to a table with columns: history_id, history_date and etc. I'm inherit DetailView class -
Axios 404 (Not Found) on first click, third click works
I've built my react application (https://carru.co) using axios to connect to my backend django server, in which I have to send a request there to get some information required for it to work, the problem I'm having is that I'm sending exactly the same request from one device but when trying to do it from other one it doesn't work, it sometimes work and sometimes don't. For example, in my pagination, I need three clicks to get it to work as is shown in the console for exactly the same values on request: At the third click the request was performed with status 200 and data was received. This is my code: nextPage = () => { let local_page = this.state.page local_page += 1 console.log('clicked next', local_page) this.setState({loading: true}) getCarFiltersPage(this.state.brands, this.state.models, this.state.filters, local_page).then( res => { this.setState({list_json: res}) this.setState({loading: false}) this.setState({page: local_page}) window.scrollTo(0, 0) } ) } Thanks in advance for any hint or help -
Uncaught TypeError: Cannot read property 'Constructor' - Django Bootstrap-datapicker
I'm getting the error "Uncaught TypeError: Cannot read property 'Constructor' of undefined at bootstrap datepicker" and the date pop up doesn't work: I start getting this error after updating all my packages to the last version on the project and after hours of research, I didn't find any solution. After I had the following versions, among others: Django==2.1.7 django-bootstrap-datepicker-plus==3.0.5 django-bootstrap4==0.0.7 Now I have the following versions: Django==3.1.7 django-bootstrap-datepicker-plus==3.0.5 django-bootstrap4==2.3.1 This is how my code is structured and was working perfectly on old packages versions: main.html: <head> (some CSS's load's) {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {% block extrahead %} {{ form.media }} {% endblock %} </head> <body> (...) {% block content %} {% endblock %} (...) <script type="module" src="{% static 'vendor/jquery-easing/jquery.easing.min.js' %}"></script> <!-- Custom scripts for all pages--> <script type="module" src="{% static 'js/sb-admin-2.min.js' %}"></script> <!-- Page level plugins --> <script type="module" src="{% static 'vendor/datatables/jquery.dataTables.min.js' %}"></script> <script type="module" src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js'%}"></script> <!-- Page level custom scripts --> <script type="module" src="{% static 'js/demo/datatables-demo.js' %}"></script> <!-- Deletes --> <script type="module" src="{% static 'js/deletes.js' %}"></script> <!-- Tables sort and search --> <script type="module" src="{% static 'js/tables-aux.js' %}"></script> <script type="module" src="{% static 'js/add_types.js' %}"></script> <script type="module" src="{% static 'js/defult.js' %}"></script> … -
How to create a requirements.txt file in Django project?
I have been trying to create a requirements.txt file from the Pycharm terminal but it is adding all unnecessary packages as well. What should I do to show only used packages? Thanks, requirements.txt: aiohttp==3.7.3 aioredis==1.3.1 alabaster==0.7.12 anaconda-client==1.7.2 anaconda-navigator==1.9.12 anaconda-project==0.8.3 appdirs==1.4.4 appnope==0.1.0 argh==0.26.2 asgiref==3.3.1 asn1crypto==1.3.0 astroid==2.4.2 astropy==4.0.1.post1 async-timeout==3.0.1 atomicwrites==1.4.0 attrs==19.1.0 autobahn==21.2.1 Automat==20.2.0 autopep8 @ file:///tmp/build/80754af9/autopep8_1592412889138/work Babel==2.8.0 backcall==0.1.0 backports.functools-lru-cache==1.6.1 backports.shutil-get-terminal-size==1.0.0 backports.tempfile==1.0 backports.weakref==1.0.post1 bcrypt==3.1.7 beautifulsoup4==4.9.1 bitarray @ file:///C:/ci/bitarray_1594751092677/work bkcharts==0.2 bleach==3.1.0 bokeh @ file:///C:/ci/bokeh_1593183652752/work boto==2.49.0 Bottleneck==1.3.2 brotlipy==0.7.0 bs4==0.0.1 certifi==2020.6.20 cffi==1.13.1 channels==3.0.3 channels-redis==3.2.0 chardet==3.0.4 cheroot==8.5.2 Click==7.0 cloudpickle @ file:///tmp/build/80754af9/cloudpickle_1594141588948/work clyent==1.2.2 colorama==0.4.4 comtypes==1.1.7 conda==4.8.3 conda-build==3.18.11 conda-package-handling==1.7.0 conda-verify==3.4.2 constantly==15.1.0 contextlib2==0.6.0.post1 cryptography==3.4.6 cycler==0.10.0 Cython @ file:///C:/ci/cython_1594830140812/work cytoolz==0.10.1 daphne==3.0.1 dask @ file:///tmp/build/80754af9/dask-core_1594156306305/work decorator==4.4.0 defusedxml==0.6.0 diff-match-patch @ file:///tmp/build/80754af9/diff-match-patch_1594828741838/work distlib==0.3.1 distributed @ file:///C:/ci/distributed_1594747837674/work dj-database-url==0.5.0 dj-rest-auth==2.1.3 Django==3.1.5 django-admin-honeypot==1.1.0 django-allauth==0.44.0 django-bootstrap4==0.0.5 django-channels==0.7.0 django-crispy-forms==1.11.0 django-defender==0.8.0 django-heroku==0.3.1 django-honeypot==0.9.0 django-tastypie==0.14.3 djangorestframework==3.12.2 dnspython==1.15.0 docutils==0.16 entrypoints==0.3 et-xmlfile==1.0.1 Faker==0.8.13 fastcache==1.1.0 filelock==3.0.12 flake8==3.7.8 Flask==0.12.4 Flask-Bcrypt==0.7.1 Flask-Cors==3.0.3 Flask-JWT-Extended==3.7.0 Flask-Login==0.4.0 fsspec==0.7.4 future==0.18.2 gevent @ file:///C:/ci/gevent_1593010772244/work glob2==0.7 gmpy2==2.0.8 greenlet==0.4.16 gunicorn==20.0.4 h5py==2.10.0 HeapDict==1.0.1 hiredis==1.1.0 html5lib @ file:///tmp/build/80754af9/html5lib_1593446221756/work hyperlink==21.0.0 idna @ file:///tmp/build/80754af9/idna_1593446292537/work imageio @ file:///tmp/build/80754af9/imageio_1594161405741/work imagesize==1.2.0 importlib-metadata==0.23 incremental==17.5.0 intervaltree @ file:///tmp/build/80754af9/intervaltree_1594361675072/work ipykernel==5.1.3 ipython==7.8.0 ipython-genutils==0.2.0 ipywidgets==7.5.1 isort==5.7.0 itsdangerous==1.1.0 jaraco.functools==3.1.0 jdcal==1.4.1 jedi==0.15.1 Jinja2==2.10.3 joblib @ file:///tmp/build/80754af9/joblib_1594236160679/work json5==0.9.5 jsonschema==3.1.1 jupyter==1.0.0 jupyter-client==5.3.1 jupyter-console==6.0.0 jupyter-core==4.4.0 jupyterlab==2.1.5 jupyterlab-server @ file:///tmp/build/80754af9/jupyterlab_server_1594164409481/work keyring @ file:///C:/ci/keyring_1593109210108/work kiwisolver==1.2.0 lazy-object-proxy==1.4.3 libarchive-c==2.9 llvmlite==0.32.1 locket==0.2.0 lxml @ file:///C:/ci/lxml_1594826940903/work … -
Can I connect a Python GUI to a website using HTTP?
Is there a way to connect to a website from a Python Tkinter GUI using HTTP requests? Essentially, I want the following functionality: Press a button on the GUI A signal is sent to a website (from the GUI) that this button was pressed Send information along with that signal I only need to focus on the GUI side of this. I have no code to go along with this - I was just wondering if it's even possible. -
Django - AWS S3 - non-predictable behavior when reading a FileField
I have a django model like so: class Segmentation(models.Model): file = models.FileField(...) ... The file is an image (of a red blob) that is stored in an AWS bucket. I am trying to do some simple computer vision logic on each file in my segmentation instances. However I noticed some very strange non-predictable behavior when reading the file using: bytes_string = segmentation.file.read() if bytes_string: # conduct simple cv logic else: # do nothing Sometimes the file reading "fails" such that bytes_string is b'' and the remaining part of the script does not execute. However, if I rerun the script the file reading may indeed be successful and the remaining part of the script executes as desired. When exactly a file reading "fails" I have yet to determine. Has anyone come across an issue like this before? The cv-script lives in a post_save signal, meaning a solution (ideally) avoids having to repeatedly run this script in order to trigger a successful file-read. -
How to run periodic tasks concurrently with Celery and Django
I have some tasks being running by celery in my Django project. I use contrab to specify the time the task should be run, like this: from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'task_a': { 'task': 'tasks.task_a', 'schedule': crontab(minute=0, hour='5,18'), }, 'task_b': { 'task': 'tasks.task_b', 'schedule': crontab(minute=4, hour='5,18'), }, } What has been happening is that one task is executed, and only about 5 minutes later the other starts. When they should be executed at the same time. I would like all of them to be started at the same, but this it's not what is happening there are about eight tasks in total, some of which take a long time to complete I am using the following command at the moment initially, it was like this celery -A api worker --concurrency=4 -n <name> then I tried celery -A api multi --concurrency=4 -n <name> and finally celery -A api multi -P gevent --concurrency=4 -n <name> They are all shared_tasks @shared_task(bind=True, name="tasks.task_a") def task_a(self): pass and I'm using autodiscover_tasks app = Celery('<app-name>') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)