Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django dynamic create form based on dropdown select
I'm working on with Django, question and how to, is there any way to generate dynamic form based on the dropdown selection? My form is really simple, user will need to update device information. Instead of submitting one form at a time, I would like to provide options with dropdown select number of devices, let say 10, there should be 10 new forms entries. Within 1 Form there are 4 fields needs to enter. I started something but stuck on view and display via html MODEL class Devices(DeviceINFO, models.Model): name = models.ForeignKey(DeviceTYPE, on_delete=models.SET_NULL, null=True) item1_link1 = models.CharField(max_length=5, blank=True, default='') item1_link2 = models.CharField(max_length=5, blank=True, default='') ... FORM: class Devices_form(forms.ModelForm): class Meta: model = Devices fields = '__all__' def __init__(self, n, *args, **kwargs): super(Devices_form, self).__init__(*args, **kwargs) for i in range(0, n): self.fields["item%d_link1" % i] = forms.CharField(max_length=20, blank=True, default='') self.fields["item%d_link2" % i] = forms.CharField(max_length=20, blank=True, default='') ... VIEW: def DevicesView(request, *args, **kwargs): template_name = 'DeviceView.html' seq = [2, 4, 6, 8, 10] form = Devices_form(request.POST or None) if request.method == 'POST': if form.is_valid(): print(form.cleaned_data['seq']) context = { 'num': form.cleaned_data['seq'] } return render(request, template_name, {'seq': seq}) Is that right way? How to display in html? Thanks for the help in advance. -
Ajax does not request the page with the written url
The problem is as follows: When I type on the address bar browser http://127.0.0.1:8000/For-Sale-Listings/Taiz http://127.0.0.1:8000/For-Sale-Listings/Lahj It gives us the correct data, but when you request the address in JEX, it sends the request without giving us the data [06/Sep/2019 10:20:49] "GET /For-Sale-Listings/Taiz HTTP/1.1" 200 304194 here [06/Sep/2019 10:21:55] "GET /For-Sale-Listings/Taiz HTTP/1.1" 200 304194 here [06/Sep/2019 10:22:32] "GET /For-Sale-Listings/Lahj HTTP/1.1" 200 303411 [06/Sep/2019 10:22:32] "GET /static/js/scriptMap.js HTTP/1.1" 304 0 It should go to the application and give us the data for each city by address This is the view code class For_Sale_Listings(DetailView): template_name = 'Main.html' def get(self, request, *args, **kwargs): print('here') self.kwargs.setdefault('city', 'Taiz') places = Place.objects.filter(city=self.kwargs['city']).values_list('listing__price', 'image_main_path','address', 'latitude', 'longitude') kwargs['places_json'] = json.dumps(list(places), cls=DjangoJSONEncoder) return render(request, self.template_name, kwargs) This is the Ajax code $.ajax({ url: '/For-Sale-Listings/'+City.name, type: "GET", success: function(data){ alert(data); console.log(data); } }); And accept my regards -
Django PageNumberPagination customize error if page number out of range
I'm currently trying to create an API that return list of objects with page and limit per page input from url parameter using django-rest-framework which i already done in my api view with custom Pagination class PropertyListPagination(PageNumberPagination): page_size = 20 page_size_query_param = 'page_size' def get_paginated_response(self, data): return Response({ 'code': 200, 'data': data }) @api_view(['GET']) def property_list(request): if request.method == 'GET': paginator = PropertyListPagination() queryset = Property.objects.all() context = paginator.paginate_queryset(queryset, request) serializer = PropertySerializer(context, many=True) return paginator.get_paginated_response(serializer.data) Currently if a page is out of range( for example if i have only 2 object and i set my url to page=3 and page_size=1 then it should out of range of total objects) then in the response it will return a 404 status and in the body: { "detail": "Invalid page." } Is there a way to customize for it to return 400 status and the following json body ? { "code": 400, "error": "Page out of range" } Thank you -
Login existing user from db to django
I am newbie in Django, and I have problem with authentication users in django. I write some code, display users, but cannot login existing user in database using login and password. I have error 403 "CSRF token missing or incorrect." views.py from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from . import dbmodel_peoples from django.template import loader from django.contrib import auth from django.template.context_processors import csrf def login(request): c = {} c.update(csrf(request)) return render(request, 'login.html ', c) def auth_view(request): username = request.Post.get('username', '') password = request.Post.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return HttpResponseRedirect('/my_app/index.html') else: return HttpResponseRedirect('/my_app/index.html') def loggedin(request): return render(request, 'index.html', {'login.peo_name': request.user.username}) urls.py urlpatterns = [ path('', views.index, name='index'), path('', views.login, name='login'), url(r'^login/$', views.login), models.py class Peoples(models.Model): peo_login = models.CharField(db_column='PEO_LOGIN', primary_key=True, max_length=50) peo_name = models.CharField(db_column='PEO_IMIE', max_length=255, blank=True, null=True) peo_pass = models.CharField(db_column='PEO_PASS', max_length=255, blank=True, null=True) login.html <form action="" method="post"> {% csrf_token %} <select list="employees" id="username" name="username"> <option hidden="">Login</option> {% for login in peoples %} <option value="{{login.peo_login}}">{{ login.peo_name }} </option> {% endfor %} </select> <br> <input placeholder="PASSWORD" value="" type="password" id="password" name="password">{{ login.peo_pass }} <br> <input type="submit" value="login" /> </form> Please, a help, how can I login users to my django app. -
Send two models to a template in django
I'm having a eCommerce web application in django and I have a base.html that my navigation bar and other stuff is included in that and other necessary templates extended from that. now I have a home.html that has a navbar that is extended from base.html and also my home page is going to show list of products. I want to show my categories from category table or model that I created and list the items from Product table or model. How should I do that??? Thanks in advance. -
Best practises in case of possibly large requested file which is needed to be fully displayed
The case Firstly I am a total beginner and unaware of web-related terminology, so sorry if this post is a duplicate. I am implementing a web app with Angular@6 and Django@2.2. In my app, I provide the users with a form with options. Based on the selected options, I request the backend for the relative results. The results are rows of the form {orderNumer: integer, message: string}. The number of rows, that the backend responds with, ranges from 0 up to 20k. The Problem and what I have done I am currently using Angular Material Table, requesting the whole file from django (no streaming) and since angular get the results, I am passing them into angular material table. The problem is that in case of 14k rows, the table displays this result with a delay of 12secs. I mean that from the time that all 14k rows are fetched to Angular from Django, there are 12 secs passed to be displayed. Some Limitations I have noticed about pagination, i.e. requesting data in chunks either when user scrolls or gets to the results next page. However, this is not the desired behavior in my app. I want the user to be … -
How to show the csv file on frontend in Django?
I am a beginner in Django and have a project of data scraping. I am trying to show CSV file on the front end. I have tried to send p_name variable to frontend but that doesn't work at all def index(request): if request.method == "POST": url = request.POST.get('url', '') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) with open('product_file.csv', mode='w') as product_file: product_writer = csv.writer(product_file) for name,price in zip(p_name,p_price): product_writer.writerow([name.text, price.text]) for name,price in zip(p_name,p_price): print(name.text) return render(request, 'index.html') `` index = <ul> {% if request.method == 'POST' %} {% for name in p_name %} <li> {% autoescape off %} {{name}} {% endautoescape %} </li> {% endfor %} {% endif %} </ul> -
Wagtail full width admin
I have the following StructBlock sections = blocks.ListBlock( blocks.StructBlock( [("header", blocks.CharBlock()), ("content", blocks.RichTextBlock())] ) ) I am using the above block in my page admin as follows: content = StreamField( [("article_sections", blocks.ArticleSectionBlock())], null=False, blank=False ) content_panels = Page.content_panels + [StreamFieldPanel("content")] In the wagtail admin, this field is very narrow and hard to use: Is there a way to make it full width in the admin to provide more space to type? -
Import Error: sessionauthtoken.authentication.SesssionTokenAuthentication
Import error, What to install to run the code? ImportError: Could not import 'sessionauthtoken.authentication.SesssionTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. AttributeError: module 'sessionauthtoken.authentication' has no attribute 'SesssionTokenAuthentication'. -
How to manually select data from database in django?
I am trying to make a management system for a hospital. I have these two models: class Case(models.Model): user = models.ForeignKey(User,default=1,on_delete=models.CASCADE) symptoms=models.CharField(max_length=60) disease=models.CharField(max_length=30, blank = True) starting_date=models.DateField(default=now) last_visit=models.DateField(blank = True) def __str__(self): return str(self.user.first_name)+"\t"+str(self.last_visit) class Visits(models.Model): case = models.ForeignKey(Case,default=1,on_delete=models.CASCADE) medicine = models.CharField(max_length=50,blank=True) progress = models.CharField(max_length=20,blank=True) Date = models.DateField(default = now) test = models.CharField(max_length=50,blank=True) temperature = models.IntegerField(blank = True) bp = models.CharField(max_length = 6, blank = True) current_status = models.CharField(max_length=60) disease = models.CharField(max_length=30,blank=True) def __str__(self): return str(self.case_id) There can be many visits to a single case, further, a user can have many cases. The user should be able to select which case he wants to create the visit for. I have no idea how to do that. I can get all the cases of the user by: cases = Case.objects.filter(user = request.user) after that, how to manually be able to link a case to a visit? -
How can I use same database for two different projects one is my python based Desktop App and another is my django app. Could you please help me?
I have a single database which I want to for my both apps one is my Python based app and another is Django project. What will be the path for my Django project if I am doing so. My whole project structure is MAIN APP --KEY (PYTHON) --PACKAGE (PYTHON) --RESOURCES (PYTHON) --DJANGO PROJECT (DJANGO) --COMMON DATABASE(THIS IS MY DATABASE THAT I WANT TO USE FOR BOTH ABOVE PACKAGES) --MAIN.PY (FILE TO GENERATE DATABASE) For this what would be the Django database path. I am new to Django so don't have that much idea about database paths although I tried various things and searched on various places but not getting exact idea. Could you please help me? -
Time picker not working rendering on the HTML page, DJANGO 2.1
I am trying to show the time picker on the html and use that data in the form using django2.1. Unfortunately, I am only able to make the datefield work, not the time picker. Based on the example, can someone show me how to use it and make it work on the form, views and html? models.py class TimeSlot(models.Model): start_date = models.DateTimeField() stop_date = models.DateTimeField() forms.py class CreateTimeSlotForm(forms.ModelForm): start_time = forms.TimeField(widget=forms.TimeInput(attrs={'class':'timepicker'})) stop_time = forms.DateField(widget=forms.DateInput(attrs={'type':'date'})) class Meta: model = TimeSlot views.py def foo(request): if request.method == 'POST': form = CreateTimeSlotForm(data=request.POST or None) if form.is_valid(): form.save() else: form = CreateTimeSlotForm() context = { 'form': form, return render(request, 'core/list.html', context) html <div class="col-sm-3 ml-3 mb-5"> <form action="." method="post" class="order-form"> {% csrf_token %} {{ form.as_p }} </br> <button class="btn btn-primary" type="submit" value="Place order">Save & Close</button> </form> </div> Thank you for your help. -
Windows authentication with permissions (from ldap?) for a Django web application
I work for a company that has a number of web applications on the intranet. All of these apps are hosted on IIS servers and users who have access to these applications are auto logged in when they open these apps. I am writing a web application in Django which will be hosted on the intranet. Now, I can do LDAP authentication with django-ldap to query the Microsoft AD service and log in specific users or I can use the "REMOTE_USER" value set by IIS to log in users using their Windows account (RemoteAuthentication backend). However, I can't seem to set permission and roles or restrict users using the RemoteAuthentication backend. Is there any way to combine the above two? I would like my users to be auto logged in to the Django app using their windows account but only the users that should have access to the Django app and also set permissions. -
Stripe UI Component not rendering correctly in Django app
I'm following an outdated course titled 'Python eCommerce Build a Django eCommerce Web Application' the instructor is informative but a lot of the syntax is outdate, which has required me to research on how to implement features using the latest version django, bootstrap and currently stripe for the checkout page. I'm reading the guidelines for using Stripe's UI Component because so much has changed since the instructor recorded the section on implementing Stripe. The issue that I am trying to resolve is the Stripe Elements are not appearing in the browser, but when I use the browser's development tools to inspect I can see that the UI Component elements are populating. I read that "the address of the page that contains Elements must start with https:// rather than http://. " so I installed runserver_plus --cert-file cert.crt. Yet the UI Component Elements are still not appearing! Also, System check identified no issues. checkout.html {% extends 'base.html' %} {% block script %} <!-- Stripe.js v3 for Elements --> <script type="text/javascript"> const stripe = Stripe('pk_test_5555555555t6mx8z8U1uS00uTestHpU'); const elements = stripe.elements(); </script> {% endblock %} {% block content %} <form action="" method="post" id="payment-form" class="StripeForm">{% csrf_token %} <div class="form-row"> <label class="StripeLabel" for="card-element"> Credit or debit card … -
How to populate a related field on selection of a choice field in inline formset
I am working on an inline formset where: a. the user will be filling the header data first b. next while in the inline section, user selects a choice field (a product name) and I want this action to trigger filling other field/s with a value from a related table (FK relationship). The related field/s will have information like the pricing items in the related field. I want this to basically facilitate user acceptance (i.e. without having to click additional buttons). I have tried a few examples from the web (like populating the price field using a query) but I am unable to capture the user selection of product from the drop down list. Tried JQuery but I am not really able to get around. How do I achieve this? -
Django local dev server hangs with chrome after form submission. Works in firefox
Ok this is a strange one. Here is what I do to reproduce the problem (windows 10/python 3.7.1/django 2.5.5): Create a new virtual env with virtualenv-wrapper and 'mkvirtualenv' command Install Django in the virtual env using 'pip install django' Create a new Django project Migrate for first time to default sqlite database createsuperuser Run dev server Access 127.0.0.1:8000/admin via chrome Log in with superuser credentials I see a http post in the dev server console window. It looks like this: (default-users) C:\Users\kmfae\Documents\test\django-default-users>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 05, 2019 - 19:13:22 Django version 2.2.5, using settings 'defusers_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [05/Sep/2019 19:13:40] "GET /admin HTTP/1.1" 301 0 [05/Sep/2019 19:13:40] "GET /admin/ HTTP/1.1" 302 0 [05/Sep/2019 19:13:40] "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1819 [05/Sep/2019 19:13:40] "GET /static/admin/css/login.css HTTP/1.1" 200 1233 [05/Sep/2019 19:13:40] "GET /static/admin/css/base.css HTTP/1.1" 200 16378 [05/Sep/2019 19:13:40] "GET /static/admin/css/responsive.css HTTP/1.1" 200 17944 [05/Sep/2019 19:13:40] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [05/Sep/2019 19:13:40] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [05/Sep/2019 19:13:40] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [05/Sep/2019 19:13:47] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 But in the chrome browser I don't get redirected … -
Filter list in Django when clicked on the option given
I am working on filtering the list (in this case it's displaying image based on the url in the database) when clicked on an option. And by this I mean I have a dropdown of character names, and by clicking on the option (name), it should return a list of displaying only the images of that certain character. I am fairly new to Django, still trying to understand the connection between urls, template and views. Any help or advice of which direction I should go for would be greatly appreciated, thanks! I have looked at the Django URL dispatcher documentation. And the URLconf example is something I'm aiming for, but I am not too sure how to pass in the value... https://docs.djangoproject.com/en/2.2/topics/http/urls/ I have also tried looking for example with filters, but it seems a lot of the filter others implemented are with entering the field, and filter based on the keyword entered. Template: {% block content %} <ul> <li><a href="#home">Home</a></li> <li class="dropdown"> <a href="javascript:void(0)" class="dropbtn">Characters</a> <form class="dropdown-content"> {% for c in character_name %} <a> {{ c.name }} </a> {% endfor %} {% endblock %} </div> </li> </ul> <div class="row"> {% for c in card_list %} <div class="column"> <div class="card"> … -
How to reference context specific processor dictionary items in a template via strings (using render_as_template)?
In Django, in my DB I've created string variables containing boilerplate HTML with dynamic URLs, and I can't quite get them to work in my templates. I'm using render_as_template so the dynamic URLs work. I tried custom template tags, but when I use those with render_as_template, it fails to load. I then tried a custom context processor. I created two functions in the context processor, one for hyperlinks, and one for tooltips. I got the tooltips processor to work, but I can only reference them in the template via their number in the auto-generated dict from the queryset. I did the same with the hyperlink processor, then tried modifying it to use string keys instead of integers, but it doesn't load all of the field. I must be missing something. custom_tags.py from django import template register = template.Library() @register.simple_tag def rdo_hyper(): value = Boilerplate.objects.filter(name='RDO').values_list('hyperlink',flat=True) return value[0] custom_context.py from myapp.apps.wizard.models import Boilerplate def boilerplate_hyperlink_processor(request): boilerplate_hyper = { "foo": Boilerplate.objects.filter(name='Aftermarket').values_list('hyperlink',flat=True), "bar": Boilerplate.objects.filter(name='Sights').values_list('hyperlink',flat=True) } return {'boilerplate_hyper': boilerplate_hyper} def boilerplate_tooltip_processor(request): boilerplate_tooltip = Boilerplate.objects.values_list('tooltip',flat=True) return {'boilerplate_tooltip': boilerplate_tooltip} template.html {% load static %} {% load custom_tags %} {% rdo_hyper as rdo_hyper %} {% load render_as_template %} ... <html> {% autoescape off %} 1. {% rdo_hyper %} … -
NoReverseMatch error. My URL is not a valid view function or pattern name despite having a URL and View associated with it
I am trying to make a form with an input button group that redirects the user to another URL given the button they pushed. I am currently receiving a NoReverseMatch when I don't think I should be. I went through the top answer of What is a NoReverseMatch error, and how do I fix it? but don't think those apply to me. The form in index.html: <form action="/main/community/" method="get"> <div class="btn-group" role="group" aria-label="Basic example"> <input type="button" class="btn btn-secondary" value='Comm1'> <input type="button" class="btn btn-secondary" value='Comm2'> <input type="button" class="btn btn-secondary" value='Comm3'> </div> </form> My URL's: app_name = 'main' urlpatterns = [ path('', views.Index, name='index'), path('community/', views.Community, name='community'), path('community/choice',views.CommView, name='CommView'), path('admin/', admin.site.urls) ] My views: def Community(request): try: pass except (KeyError): pass else: return HttpResponseRedirect(reverse('community/choice')) def CommView(request): return HttpResponse("Test success!.") When I press the buttons no redirect occurs. When I manually input the URL of /community/choice/ I receive the following error: NoReverseMatch at /main/community/ Reverse for 'community/choice' not found. 'community/choice' is not a valid view function or pattern name. -
Issue in uploading image file through test.py in DJango
Trying to populate a table having a column models.ImageField(upload_to='dataset/', blank=True) the directory dataset is created when I upload image. but after that 'OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect:' is throwing and the image is not saved in the directory 'dataset'. 'J:\BIOMETRICS\Student_projects\Biometric-ID-app\Biometric_App\biomteric_app\version 1.0 impl\biometric_app_root\media\dataset\C:' this is the url trying to create and throwing the error -
Multiple file uploads with Django form
I'm trying to write an app that can handle uploading multiple files at a time. I had the app working for a single file upload, but adding a loop to process a list of files hasn't worked yet. #models.py class image(models.Model): filename = models.CharField(max_length=100, blank=False, null=False) image = models.ImageField(upload_to='images/') uploaded_at = models.DateTimeField(auto_now_add=True) Form: class ImageForm(forms.ModelForm): class Meta: model = image fields = ('image',) widgets = {'image': forms.ClearableFileInput(attrs={'multiple':True}),} # Added to allow multiple file selections in one dialog box And relevant part of views.py: def image_upload(request): if request.method == 'POST': for f in request.FILES.getlist('image'): formI = ImageForm(request.POST, f, instance=image()) if formI.is_valid(): fs = formI.save(commit=False) fs.filename = f fs.user = request.user fs.save() (There's other stuff going on in the view, but it currently breaks before that). The result is the error: AttributeError: 'TemporaryUploadedFile' object has no attribute 'get' from the line: if formI.is_valid(): I originally had formI = ImageForm(request.POST, f, instance=image()) with request.FILES instead of f, and it seems likely that change is what's breaking this. What should I have instead of those two options? request.FILES results in only one image out of the selected being uploaded. What is the correct object to pass to ImageForm? Using Python 3.6.8 and Django 2.2.4 -
Django 2.2.5 'NoneType' object has no attribute 'lower' when performing Sum Distinct. Was working on Django 2.1.7
My application uses this rather simple model, to access data from an existing table: class Table01(models.Model): id = models.IntegerField(primary_key=True) fecha = models.DateField(blank=True, null=True) sucursal = models.IntegerField(blank=True, null=True) remito = models.IntegerField(blank=True, null=True) codcli = models.IntegerField(blank=True, null=True) razon = models.CharField(max_length=25, blank=True, null=True) domi = models.CharField(max_length=25, blank=True, null=True) turno = models.IntegerField(blank=True, null=True) codart = models.TextField(max_length=6, blank=True, null=True) canti = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) precio = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True) tot = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = "TABLE01" app_label = "datatables" The backend for this database is SQLite With Django 2.1.7 and this model, my application was performing successfully the following query: sumrem = (Table01.objects.filter(fecha = some_date, turno = some_turno, codcli =some_customer).values("fecha", "turno", "sucursal", "remito", "razon") .annotate(Sum(F("tot"), distinct=True))) to get the distinct sum of the 'tot' field, which was working as expected on Django 2.1.7 When I upgraded to Django 2.2.5, this error appeared: Python 3.7.3 (default, Apr 3 2019, 05:39:12) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from .models import Table01 >>> from django.db.models import F, Sum, Count >>> sumrem = Table01.objects.filter(fecha='2019-05-10', turno=4, codcli=50).values("fecha", "turno", "sucursal", "remito", "razon").annotate(Sum(F("tot"), distinct=True)) Traceback (most recent call last): File "<console>", line 1, in … -
Docker Role for postgres doesn't exist with django
I'm running a docker container that takes a postgres database from another host. It looks like my docker compose file is connecting to the database but when i run docker exec -it container python manage.py makemigrations or docker exec -it container python manage.py createsuperuser i get 2019-09-05 23:25:33.553 UTC [29] FATAL: password authentication failed for user "postgres_user" db_1 | 2019-09-05 23:25:33.553 UTC [29] DETAIL: Role "postgres_user" does not exist. db_1 | Connection matched pg_hba.conf line 95: "host all all all md5" db_1 | 2019-09-05 23:26:27.289 UTC [30] FATAL: password authentication failed for user "postgres_user" db_1 | 2019-09-05 23:26:27.289 UTC [30] DETAIL: Role "postgres_user" does not exist. db_1 | Connection matched pg_hba.conf line 95: "host all all all md5" Here is the db portion of my docker compose file db: image: postgres environment: - POSTGRES_HOST=host_ip - POSTGRES_USER=postgres_user - POSTGRES_PASSWORD=bad_password - POSTGRES_DB=postgres_database - POSTGRES_PORT=5432 ports: - "5434:5432" volumes: - postgresql-data:/var/lib/postgresql/data restart: always Here is my db settings in my settings.py 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres_database', 'USER': 'postgres_user', 'PASSWORD':'bad_password', 'HOST': 'db', 'PORT': '5432', } } Running psql host_db_ip -U postgres_user -W works fine and I'm able to connect. I tried removed all docker images, containers, and systems and rebuilding everything. My guess … -
Django channels connect one client without browser
I implemented Django channels tutorial and it's working ok. I have a Django app and two clients connect to the same room correctly exchanging messages. Now I'm searching for a solution where one these clients to connect automatically and without using a browser. I want e.g. that such client replies automatically given a specific message and I need that such "calculation process" takes place from the client-side. Any idea how can I implement such a feature? -
Saving a celery task (for re-running) in database
Our workflow is currently built around an old version of celery, so bear in mind things are already not optimal. We need to run a task and save a record of that task run in the database. If that task fails or hangs (it happens often), we want to re run, exactly as it was run the first time. This shouldn't happen automatically though. It needs to be triggered manually depending on the nature of the failure and the result needs to be logged in the DB to make that decision (via a front end). How can we save a complete record of a task in the DB so that a subsequent process can grab the record and run a new identical task? The current implementation saves the path of the @task decorated function in the DB as part of a TaskInfo model. When the task needs to be rerun, we have a get_task() method on the TaskInfo model that gets the path from the DB, imports it using getattr, and another rerun() method that runs the task again with *args, **kwargs (also saved in the DB). Like so (these are methods on the TaskInfo model instance): def get_task(self): """Returns …