Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
heroku logs --tail : gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
I have just deployed my Django app to Heroku but it is not running. I checked the logs and found this error: 2019-11-01T22:07:40.39246+00:00 app[web.1]: Traceback (most recent call last): 2019-11-01T22:07:40.392462+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2019-11-01T22:07:40.392465+00:00 app[web.1]: worker.init_process() 2019-11-01T22:07:40.392467+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process 2019-11-01T22:07:40.392469+00:00 app[web.1]: self.load_wsgi() 2019-11-01T22:07:40.392471+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2019-11-01T22:07:40.392472+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2019-11-01T22:07:40.392475+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2019-11-01T22:07:40.392476+00:00 app[web.1]: self.callable = self.load() 2019-11-01T22:07:40.392478+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2019-11-01T22:07:40.39248+00:00 app[web.1]: return self.load_wsgiapp() 2019-11-01T22:07:40.392482+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2019-11-01T22:07:40.392484+00:00 app[web.1]: return util.import_app(self.app_uri) 2019-11-01T22:07:40.392486+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app 2019-11-01T22:07:40.392488+00:00 app[web.1]: __import__(module) 2019-11-01T22:07:40.392489+00:00 app[web.1]: File "/app/pur_beurre/pur_beurre/wsgi.py", line 16, in <module> 2019-11-01T22:07:40.392492+00:00 app[web.1]: application = get_wsgi_application() 2019-11-01T22:07:40.392494+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-11-01T22:07:40.392495+00:00 app[web.1]: django.setup(set_prefix=False) 2019-11-01T22:07:40.392497+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 19, in setup 2019-11-01T22:07:40.392499+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2019-11-01T22:07:40.392502+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ 2019-11-01T22:07:40.392503+00:00 app[web.1]: self._setup(name) 2019-11-01T22:07:40.392505+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 66, in _setup 2019-11-01T22:07:40.392507+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2019-11-01T22:07:40.392509+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 157, in __init__ 2019-11-01T22:07:40.392511+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2019-11-01T22:07:40.392513+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2019-11-01T22:07:40.392516+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2019-11-01T22:07:40.392518+00:00 … -
clean_title() missing 1 required positional argument: 'title'
clean_title() missing 1 required positional argument: 'title' I see this problem and i don't know how to solve it. Can you pls help me? Here some parts of my models.py class Post(models.Model): kategori= models.ManyToManyField(Category,related_name='post',verbose_name='Kategoriler',help_text='Başlık giriniz') title= models.CharField(max_length=120,blank=False,verbose_name='Başlık',help_text='Baslik giriniz') slug = models.SlugField(max_length=122,default='', null=False, verbose_name='Slug Alani',editable=True) icerik= models.TextField(verbose_name='icerik',help_text='İcerik giriniz') def __str__(self): return '%s' % (self.title) def get_slug(self): return self.slug def unique_slug(self,new_slug, orijinal_slug, index,): if Post.objects.filter(slug=new_slug): new_slug='%s-%s' %(orijinal_slug,index) index+=1 return self.unique_slug(new_slug=new_slug, orijinal_slug=orijinal_slug, index=index) return new_slug def save(self, *args, **kwargs): if self.slug =='': index = 1 new_slug = slugify(self.title) self.slug = self.unique_slug(new_slug=new_slug , orijinal_slug= new_slug , index=index) #self.slug=slugify(self.title) super(Post, self).save(*args,**kwargs) here view page def post_create(request): post_form= PostForm() if request.method=='POST': post_form= PostForm(request.POST,request.FILES) if post_form.is_valid(): created_post =post_form.save(commit=True) messages.success(request,'Post Oluşturuldu') return HttpResponseRedirect(reverse('posts:post_detail',kwargs={'slug':created_post.get_slug(self='title')})) return render(request,'posts/post_create.html',context={'form':post_form}) TypeError at /posts/create/ clean_title() missing 1 required positional argument: 'title' Request Method: POST Request URL: http://127.0.0.1:8000/posts/create/ Django Version: 2.2.6 Exception Type: TypeError Exception Value: clean_title() missing 1 required positional argument: 'title' Exception Location: C:\Users\EMREKA~1\Desktop\myblog\myenv\lib\site-packages\django\forms\forms.py in _clean_fields, line 402 Python Executable: C:\Users\EMREKA~1\Desktop\myblog\myenv\Scripts\python.exe Python Version: 3.7.5 Python Path: ['C:\Users\EMRE KARACA\Desktop\myblog', 'C:\Users\EMREKA~1\Desktop\myblog\myenv\Scripts\python37.zip', 'C:\Users\EMREKA~1\Desktop\myblog\myenv\DLLs', 'C:\Users\EMREKA~1\Desktop\myblog\myenv\lib', 'C:\Users\EMREKA~1\Desktop\myblog\myenv\Scripts', 'c:\users\emre karaca\appdata\local\programs\python\python37\Lib', 'c:\users\emre karaca\appdata\local\programs\python\python37\DLLs', 'C:\Users\EMREKA~1\Desktop\myblog\myenv', 'C:\Users\EMREKA~1\Desktop\myblog\myenv\lib\site-packages'] -
Celery worker hangs with 100% cpu randomly
I'm in the process of moving a rather large router configuration parser from a nighly cron job to a series of celery tasks ~18000 scheduled through celery beat as part of a Django application. When the code was being ran through a Django management command using a multiprocessing pool we encountered no issues and it would successfully complete each night. When moved into a debian-buster python 3.6.9 container using celery as our task queue, at random celery workers would start spiking to 100% CPU indefinitely and never recover until the process is killed and restarted. When this condition occurs attaching strace to the process gives no output to debug the culprit. I've attached it for up to 30 minutes and never had anything print to the console. This happens completely at random. Targeting a router which previously caused the CPU spike, will successfully complete without issue. The script will log into a router, run a series of commands and collect the output. The output is then parsed, stale data is deleted from the database and replaced with current data. We are parsing interface configurations and multicast route tables from a variety of vendors. The script when ran through celery will … -
Where to handle PDF creation in a Django React site
I have a site that uses Django REST framework for the backend, react for the frontend, and axios to handle requests between them. I want my site to be able to create PDFs for the users. I looked on the web and found that I can create PDFs through both Django and React. I am wondering which one I should use to handle the PDF creation. -
Unknown database engine mysql.connector.django
I'm trying to reset the database on django (python manage.py reset_db) but django complains with CommandError: Unknown database engine mysql.connector.django. I've already run pip install mysql-connector-python and sudo apt install python-mysqldb but no luck. How can I get this error to magically disappear? FYI: My config has the database->default->engine set to "mysql.connector.django". -
Django CheckboxSelectMultiple map to another field to save in model
I have a rather complicated template. It has CheckboxSelectMultiple for three models and I can save them fine without any problems. class DocAideForm(forms.ModelForm): class Meta: model = DocAide fields = ['no_charge', 'doctors_notes', 'scan', 'part_to_xray', 'part_to_scan', 'test', 'drug', 'qty'] widgets = { 'scan': forms.CheckboxSelectMultiple(), 'test': forms.CheckboxSelectMultiple(), 'drug': forms.CheckboxSelectMultiple() } This is the form and in the template I am using them one by one. Like this: {% for form in forms %} {% for fields in form %} <tr><td width="10000"> {{ fields.label }} </td> <td>{% if fields|length < 3 %} {{fields}} {% else %} <table class="table table-hover table-striped table-bordered" align="center"><tr> {% for field in fields %} {% if forloop.counter0|divisibleby:5 %} <tr> {% endif %} <td>{{ forloop.counter }}</td><td>{{ field }} {% if fields.label == "Drug" %} Qty: 1+ {% endif %} </td> {% endfor %}</tr> </tr></table> {% endif %} </td> {% endfor %} {% endfor %} Where the quantity is I would like to have the IntegerField of the Qty. As to how many drugs are going to be described. In views.py I do it like this: if doc_aide_from.cleaned_data['drug']: p = Prescription(patient=patient) p.save() p.drug.add(*list(doc_aide_from.cleaned_data['drug'])) Again this works fine. But with the Qty field now I would like to have it for each … -
Pass Text From Model/Middleware To Template
How do I go about passing the reason to banned.html from the UserBanning model from the middleware? Everything works but I want to display the reason. models.py: from django.db import models from django.contrib.auth.models import User from django.conf import settings class UserBanning(models.Model): user = models.ForeignKey(User, verbose_name="Username", help_text="Choose Username", on_delete=models.CASCADE) ban = models.BooleanField(default=True, verbose_name="Ban", help_text="Users Bans") reason = models.CharField(max_length=500, blank=True) class Meta: verbose_name_plural = "User Banning" ordering = ('user',) def __str__(self): return f"{self.user}" middleware.py: from .models import UserBanning from django.shortcuts import render class BanManagement(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) banned = UserBanning.objects.all() context = { 'banned': banned, } if(banned.filter(ban=True, user_id=request.user.id)): return render(request, "account/banned.html", context) else: return response banned.html: {% extends "base.html" %} {% block content %} <p>Your account has been banned. Reason: {{ banned.reason }}</p> {% endblock content %} -
Django - Autofill form data when validation error occurs in signup form
In my Django project, I allow a user to signup by completing a form I have created in HTML and not using Django forms . If a user makes an error, I re-render the page and pass an error through in a dictionary. In my template I then perform an If statement checking whether there is an error, and then If so I display that error once the page has been re-rendered. The problem I have is that if the user enters a valid email address and username, and then enters an incorrect password, then all the form data is lost when the page gets re-rendered. What I want is that if the user enter a valid username and email, and an invalid password, vice versa, then re-render the page and also autofill the fields in the form that were valid(e.g in this case the username and email field). Does anybody know how to accomplish this? Thank you. -
How to save django model objects with foreign keys which isnt exist
I have two models class League(models.Model): league_id = models.IntegerField(primary_key=True) class Fixture(models.Model): league_id = models.ForeignKey('League',null=True, on_delete=models.SET_NULL) Fixture model relate on League model with league_id foreign key field. I want to create objects of Fixture class and when i trying to create them i understand that i can't to do it because my fixture model relate to league model which hasn't values. I googled about this problem and found that it is most popular problem in Django. Can anyone give me advise how i should create this kind of objects which relate on doesnt exist models -
Hexadecimal value is shown in redis server
I am using django-redis library in django.I am trying to store data in redis server using the following code #settings.py CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', }, } } #views.py from django.core.cache import cache @action(detail=False) def get_random_questions(self, request): questions = Question.objects.all() cache.set('foo', 'bar') serializer = self.get_serializer(questions, many=True) return Response(serializer.data) and when I execute the "scan 0" command in the redis-cli I get the following response 1) "0" 2) 1) "example:1:foo2" 2) "example:1:foo" 3) ":1:foo2" 4) ":1:foo" 5) "test" 6) ":1:foo1" 7) "example:1:foo1" 8) "employee" I am not able to understand where :1:foo came from. And when I am using "get :1:foo" command, I am getting the following response "\x80\x04\x95\b\x00\x00\x00\x00\x00\x00\x00\x8c\x04bar\x9". Again I don't understand why is this happening? -
Django - Search in generated form
so I have a class "Business" and a Form / View to add a specific model which requires a business to be selected. I used: class make_xy(Form): fields = ['business'] Now I want users to be able to enter a searchstring to filter they objects presented. So altered to the following: class make_xy(Form): Search = forms.CharField(required=False) Business = forms.ModelMultipleChoiceField(queryset=Business.objects.all()) But I ran into multiple problems. So now my question: How would you build a form where users can search for a matching aspect (i.e. name) and will be presented with the matching objects so they can select one of them -
How do I apply a function to an certain object?
I want to create a method that works on a method, like this, inside the 're' python module: _compile(pattern, flags).finditer(string) the function finder is being applied on _compile, How? does the return type of _compile is string, and if it's so how can it possible to create methods that applies on strings? -
Check if a list exists in my database by querySet django
I'd like to verify if a list of variables exist in my database I tried this: if Magazine.objects.filter(mag=post.mag_no, prodc_magt_no__in[post.cn1,post.cn2,post.cn3,post.cn4) but this queryset is check at least one value, I wanna check the whole list:post.cn1,post.cn2,post.cn3,post.cn4 in my database column = prodc_magt_no note: mag=post.mag_no is necessary! -
django : Update two models using same API call
I have an API call which gets and receives the user data, User model looks something like this - I have a model for user - { "id": 23, "name": "fname", "height": null, "weight": "59", "blood_pressure": "131", "blood_sugar": "320", "email": "m@gmail.com", } I want to save this data to be saved in UserBody model - "height": null, "weight": "59", "blood_pressure": "131", "blood_sugar": "320", while I want rest of the data(id, name, email) to be saved in BodyModel My User model looks like this - class MyUser(AbstractBaseUser, PermissionMixin): name = models.CharField(max_length=63, blank=True) height = models.IntegerField(blank=false, null=false) weight = models.IntegerField(blank=true, null=false) blood_pressure = models.IntegerField(blank=true, null=false) blood_sugar = models.IntegerField(blank=true, null=false) email = models.CharField(max_length=63, blank=True) Class UserBody - class UserBody(AbstractBaseUser, PermissionMixin): user = models.OneToOneField(MyUser, on_delete=models.CASCADE) height = models.IntegerField(blank=false, null=false) weight = models.IntegerField(blank=true, null=false) blood_pressure = models.IntegerField(blank=true, null=false) blood_sugar = models.IntegerField(blank=true, null=false) I fiddled with making the user object foreignKey but I just can't wrap my head around how it should have worked. I have a MyUser serializer, but I just don't know how to write a serializer for UserBody model. Help me with any direction, I will take it forward from there. -
Django annotate complex subquery count
I have the following model: class Visit(models.Model): ... device_id = models.CharField(...) created_at = models.DateTimeField(auto_now_add=True) ... This model basically denotes a visit to a place, device_id uniquely identifies a person, and same person can visit a place multiple times, hence creating multiple enties in this table. I'm building analytics methods on top of this model. One thing I want to do is, for the last 30 days, display number of people that visitied only once within that day. With a basic approach, I can issue a db query for every single day like this: for date in dates: start_time = date end_time = date + datetime.timedelta(days=1) Visitor.objects.filter( site__in=node_descendants, created_at__gte=start_date, created_at__lt=end_date) ).values('device_id').annotate(visit_count=Count('device_id')).filter(visit_count=1).count() Now I want to calculate data for each day in the 30 day range with a single query, using a Subquery like this: single_visitor_query = Visitor.objects.filter( created_at__date=OuterRef('truncated_date') ).order_by().values('device_id') .annotate(visit_count=Count('device_id')).filter(visit_count=1) .annotate(count=Count('*')).values('count') chart_data_query = Visitor.objects.filter( created_at__gte=start_date, # Start of month created_at__lt=end_date, # End of month ).annotate( truncated_date=TruncDay('created_at') ).values('truncated_date').distinct().annotate( single_visitor_count=Subquery(single_visitor_query[:1], output_field=PositiveIntegerField() ) I have a couple of problems with this approach: count resulting from the subquery is not the count of all items having visit_count=1, but they are all 1. I know the subquery is somewhat off, but I can't see how I … -
Filtering querysets for nested models
Stack Overflow world! I am making a News App API and I want to create an APIView with comments for a speicific Post that also lets users posting comments for the specific post. These are my models (simplified): Post: class Post(models.Model): title = models.CharField(max_length=250) text = models.TextField() Comment: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = models.TextField() And view: class CommentList(generics.ListCreateAPIView): queryset = Comment.objects.filter(post=???) serializer_class = CommentSerializer First, how do I create a list of comments for an instance of Post? Second, is it the correct approach or should I try something else? -
getting info through API calls and authenticating
I want to make a Website that makes API calls to a server i have bought and we get back details about a user and use those details to create a authentication system. i need to use these few lines to do it import requests url = "*************.com.login" querystring = {"username":"username","password":"password"} response = requests.request("GET", url, headers=headers, params=querystring) jData = response.json() i ham trying to integrate this with the inbuilt django authentication system. How should i do it. any help appreciated Thanks.. i have tried something like this class AuthenticationBackend(backends.ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): usermodel = get_user_model() try: #user = user.objects.get(username=username) # API Call lms_url = "http://"*************.com/login" querystring = {"username":username,"password":password} #queryString = {"username":username,"password":password} response = requests.request("POST", lms_url, params=querystring) jData = json.loads(response.text) if jData['code'] == '200': user = User.objects.get(username=username) return user else: return None url = "*************.com/login" querystring = {"username":"username","password":"password"} response = requests.request("GET", url, headers=headers, params=querystring) jData = response.json() -
Django: Group by model parameter and Count
I have 2 models: class FaultType(models.Model): name = models.CharField(max_length=255, blank=False, default='') visible = models.BooleanField(default=True) And class RunFault(models.Model): run = models.ForeignKey(Run, on_delete=models.CASCADE) fault_type = models.ForeignKey(FaultType, on_delete=models.CASCADE) note = models.CharField(max_length=100, blank=True, default='') I need to group all instances of RunFault by FaultType, and count them. Preferably obtain a dictwith structure (example): faults = { "some_fault" = 7, "foo_fault" = 4, "bar_fault" = 13 } (Where "blabla_fault" is FaultType.name) Right now I'm querying the DB like so: faults = RunFault.objects.values('fault_type__name').order_by('fault_type').annotate(count=Count('fault_type__name')) But that returns a list of dicts like so: faults = [ {"fault_type__name": "some_fault"}, {"count": 7}, {"fault_type__name": "foo_fault"}, {"count": 4}, {"fault_type__name": "bar_fault"}, {"count": 13} ] Is that the intended behaviour of .annotate(count=Count('some_key')) ? Or am I doing the wrong query? -
Django Rest Framework Update model on POST
I am working with an api that uses POST to both create and update data, I am trying to get rest_framework to use update_or_create to check to see if the object is there before just objects.create(). I want to override the create function in the ModelSerializer class but I cant get it to update, whenever I make a POST request it just gives me a 400 error already exists Here is my serializer from rest_framework import serializers from metrics.models import * # Company Serializer class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = "__all__" def create(self, validated_data): company, updated = Company.objects.update_or_create(**validated_data) company.save() return company Viewset from metrics.models import * from rest_framework import viewsets, permissions from .serializers import * import json # Company Viewset class CompanyViewSet(viewsets.ModelViewSet): queryset = Company.objects.all() permissions_classes = [ permissions.AllowAny ] serializer_class = CompanySerializer -
How to pass data through the url in Django 2.2 and how to get the data using an AJAX get
My Django URL: urlpatterns = [ re_path(r'^data/change_title/$', views.changeAbstractTitle, name='changeAbstractTitle') ] This is the HTML table row that I am refering to with the AJAX: <td><a href="{{ item.get_absolute_url }}" id="outer_title" pmid={{ item.pmid }}>{{ item.abstractTitle }}</a></td> <tr style="background-color:white;border-style:solid;border-color:#DDDDDD;border-width:1px"> <th style="padding:10px;">Abstract Title</th> <td style="padding:10px;"><input id="abstract_title" pmid={{ item.pmid }} type="text" size="60" value="{{ item.abstractTitle }}"></td> <td style="padding:10px;"><input id="send" class="btn btn-success" onclick="change_title({{ item.pmid }} , '{{ item.subjectArea_id }}')" type="submit" value="Submit" style="padding:10px;"></td> </tr> This is my AJAX method: function change_title(pmid, subjectArea_id) { $.ajax({ url: `/data/change_title/?id=${pmid}` + `&subjectArea_id=${subjectArea_id}` + "&abstract_title=" + $(`[id*=abstract_title][pmid*=${pmid}]`).val(), type: 'GET', success: function (data) { $(`[id*=outer_title][pmid*=${pmid}]`).html(data["new_title"]); }, error: function (data) { alert("Unable to communicate with 2.7 Backend"); } }); } I am not sure how to pass the data through the URL so I can get it with my Ajax function. I am using Django 2.2. Thank you so much for your help. -
can i add Paginator to search result with chain (multiple models ) using django?
i'm asking if i can add Paginator to search result with chain (multiple models ) using django if yes how to do that please ? any idea will help me , -
Django: How to request data and simultaneously have it editable
I have a simple app that gets user input and when a button is clicked, the input is saved as an entry on the database. I'm thinking of creating another app that not only displays the same information (think of view profile) but also simultaneously lets the user edit the text that is displayed in the text field. I'm guessing the solution is to have the text-fields be auto-filled by pulling the data from the database, and allow overwriting the data once the submit button is clicked. -
Show a list of Posts in a different URL
Django comes with an out of the box index.html where it shows a list of all posts. I need to show this list in a new URL, when I somply copy the html code from index.html and paste onto planoacao.html it doesn´t show anything. This is the index.html: {% for post in post_list %} <div class="card mb-4" style="width: 18rem; "> {% if post.get_finalizado_display == 'Não' %} <!--<p class="card-text text-muted h6"> NOK </p>--> <div class="card-body" style="background-color:#FF0909;"> {% else %} <!--<p class="card-text text-muted h6"> ok </p>--> <div class="card-body"> {% endif %} {% endfor %} This is my views.py: from django.views import generic from .models import Post class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' class Calendar(generic.DetailView): model = Post template_name = 'calendar.html' class Planoacao(generic.DetailView): model = Post template_name = 'planoacao.html' This is my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), url(r'^planoacao/', TemplateView.as_view(template_name="planoacao.html")), url(r'calendar', TemplateView.as_view(template_name="calendar.html")), url(r'^admin/', admin.site.urls), url(r'^', include('blog.urls'), name="Blog"), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) How can I show a list of all posts in a different URL? xxx/planoacao.html ? Simply copying the html from index.html doesn´t work. Note that I don´t want to change the regular index.html post list, I just want … -
Forms are not getting deleted from formset after is_valid() check
I have forms that can be dynamically added and deleted from a formset. On the front end, I mark deletion by checking the "delete" checkbox included in the form. form-0-DELETE gets added to the POST automatically. https://docs.djangoproject.com/en/2.2/topics/forms/formsets/#dealing-with-ordering-and-deletion-of-forms Deleting form from django formset def edit(request): Formset = formset_factory(EditForm, extra=1, can_delete=True) if request.method == 'POST': formset = Formset(request.POST) if formset.is_valid(): cleaned_data = formset.cleaned_data print(cleaned_data) return render(request, '/edit.html', {'test': 'Post'}) else: formset = Formset() return render(request, '/edit.html', {'formset': formset}) Here is part of the return formset: data: {u'form-MAX_NUM_FORMS': [u'1000'], u'form-0-test': [u'72'], u'form-0-DELETE': [u'on'], u'form-TOTAL_FORMS': [u'0'], u'form-INITIAL_FORMS': [u'0'], u'form-0-weight': [u'1']} deleted_forms: [] 'test' and 'weight' are input values in the forms. You can see 'form-0-DELETE' there. Meaning the delete event was added to the POST with the default value 'on.' One of my links said to change this value to something that could be evaluated to true, setting it to True, true, and 1 didn't change anything. TOTAL-FORMS is correctly 0 as I keep track of additions and deletions, but I would expected deleted_forms to be populated with form-0. This is a problem when I have more than 0 forms, as I don't know what will be in cleaned data since deleted forms aren't … -
Django steps or process logging via REST
For learning purpose I want to implement the next thing: I have a script that runs selenium for example in the background and I have some log messages that help me to see what is going on in the terminal. But I want to get the same messages in my REST request from Angular app. print('Staring') print('Logged in') ... print('Processing') ... print('Success') In my view.py file class RunTask(viewsets.ViewSet): queryset = Task.objects.all() @action(detail=False, methods=['GET'], name='Run Test Script') def run(self, request, *args, **kwargs): task = task() if valid['success']: return Response(data=task) else: return Response(data=task['message']) def task() print('Staring') print('Logged in') ... print('Processing') ... print('Success') return { 'success': True/False, 'message': 'my status message' } Now it shows me only the result of the task. But I want to get the same messages to indicate process status in frontend. And I can't understand how to organize it.