Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django data frame automatically Add column
I'm creating a new data frame from my query. inputs =Test.objects.filter(created_at__date=datetime.today().date() - timedelta(days=1)).values('id','input') for i in inputs: name = name.objects.get(id=i['input']) name_label = name.label df = pd.DataFrame() df["Date"] = [datetime.today()] df["User"] = [user] df[name_label] = ['value']` Let say the query have 10 inputs(Name1,Name2,Name3,....), But my code not created a new columns depends on the query. Instead I got the only last record `{ "Name": { "Inputs": { "Date" : 2022-01-01, "User" : Admin, "Name10": "value" } } } ` I expecting output like this. The column to be added it's depend on the query output. `{ "Name": { "Inputs": { "Date" : 2022-01-01, "User" : Admin, "Name1": "value", "Name2": "value", "Name3": "value", "Name4": "value", "Name5": "value", and so on. } } }` -
how to us the prefix if there are two forms and one submit button?
I try to upload two forms with one submit button. A user can select a pdf file and a excel file. And then uploading both files. And then the contents of both are returned. So I try to upload both files with one submit button. But the two selected file options are not visible for uploading the files. So I have the template like this: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{form1.as__p}} <button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </div> <div class="d-grid gap-3"> <div class="form-group"> {{form2.as__p}} </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{conten_excel}}</textarea> </div> </div> </div> </form> </div> </span> </div> </body> </html> {% endblock content %} and the views.py: class ReadingFile(View): def get(self, *args, **kwargs): form = [UploadFileForm(), ExcelForm()] return … -
DJango Signals with Custom Arguments
I am trying to learn how to work with Django signal and maybe what I want to make work is impossible. I have two models User and Client. I want to create a Client and then use that Client ID to create a User. How do I pass user details to my signal? signals.py def client_created_handler(*args, **kwargs): print(args, kwargs) views.py client_query = Client.objects.create(client_name=request.POST.get('client_name'), address=request.POST.get('address'), email=request.POST.get('client_email'), phone='12345', website=request.POST.get('web'), created_by=request.user) custom_signal_kwargs = { "email": request.POST.get('contact_email'), "first_name": request.POST.get('first_name'), "last_name": request.POST.get('last_name'), "client": client_query, "user_role": 'Super User'} post_save.connect(client_created_handler,Client,**custom_signal_kwargs) The error I am getting is : TypeError: ModelSignal.connect() got an unexpected keyword argument 'email'. What am I doing wrong? -
Nginx setup with Django can’t access page
I have setup Django, Gunicorn and nginx. But my site is not loading? Gunicorn is running. In the logs I see that static files aren’t found. Here is my settings, am I doing something wrong with collectstatic? python manage.py collectstatic created a dir ‘collect_static’ automatically?! Before this command I had only a ‘static’ folder. Here is my Django settings, nginx settings and tree of django files: https://dpaste.org/NtoQ4 Thnx in advanced. -
Updating values inside a python list
ItemList = [ {'name': 'item', 'item_code': '473', 'price': 0}, {'name': 'item', 'item_code': '510', 'price': 0}, {'name': 'item', 'item_code': '384', 'price': 0}, ] data_1 = '510' data_2 = 200 def update_item(data_1, data_2): for a in ItemList: if a['item_code'] == data_1: update_price = append(a['price'].data_2) return True I want to update the price by using the function update_item. It fails at update_price = append(a['price'].data_2) -
Having "make_aware expects a naive datetime" while migrate
I have developed an application with Django. This is working fine in my PC with sqlite backend. But when I am trying to go live with linux server and mysql backend then I am getting bellow error while first time migration. (env-bulkmailer) [root@localhost bulkmailer]# python3 manage.py migrate Traceback (most recent call last): File "/var/www/bulkmailer-folder/bulkmailer/manage.py", line 22, in <module> main() File "/var/www/bulkmailer-folder/bulkmailer/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/core/management/commands/migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/migrations/loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/migrations/recorder.py", line 82, in applied_migrations return { File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/models/query.py", line 394, in __iter__ self._fetch_all() File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/models/query.py", line 1866, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/models/query.py", line 117, in __iter__ for row in compiler.results_iter(results): File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/models/sql/compiler.py", line 1336, in apply_converters value = converter(value, expression, connection) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/db/backends/mysql/operations.py", line 331, in convert_datetimefield_value value = timezone.make_aware(value, self.connection.timezone) File "/var/www/bulkmailer-folder/env-bulkmailer/lib64/python3.9/site-packages/django/utils/timezone.py", … -
Why Django 4.0 can access static files only with STATICFILES_DIRS, not STATIC_ROOT
When I use STATIC_ROOT: STATIC_ROOT = BASE_DIR / 'static' Django cannot access static files and always return 404 error for them. But when I use STATICFILES_DIRS: STATICFILES_DIRS = [ BASE_DIR / "static", ] Everything works well. What's the issue? I don't understand why Django works in this way, I always thought that STATIC_ROOT is correct way of creating route. -
Which Is best method to display a dynamic html table using Django and want to export data to excel after filter?
I'm new to python and Django, already I know basics of Django and I developed a website using it. The website contains html table and now a new requirement pop up, ask is to add pagination and add filters to all the column and add export option that exports filtered data to excel/csv format. I don't know, can we filter table without refreshing the webpage just using Django? or do we need Ajax & Jquery for it? or is their any better method?, Note: provide me best and latest solution that I can adopt with Django, don't like to have many dependencies and it should work across browsers and platforms. I'm using Django version 3.2.16 and don't want to use django-tables2 module -
django view list of items making them editable
I am listing the rows of a table (fields: Name, Emails, Category, Expiry) via a template: <table border="1" style="width:100%"> <tr> <th style="width:20%">Name</th> <th style="width:40%">Emails</th> <th>Category</th> <th>Expiry </th> <th>Action</th> </tr> {% for obj in expiredlist %} <tr> <td>{{obj.name}}</td> <td>{{obj.emails}}</td> <td>{{obj.category}}</td> <td>{{obj.expiry}}</td> </tr> {% endfor %} </table> Now I want to allow users to edit one of the fields on the fly (like how we do it in datatable). I tried to add a new column by adding: <td><form method="post"> {{form.expiry}} </form> <input type="submit" value="Submit"></td> Thinking that the above will allow users to edit expiry field on the fly. I know I am not passing any info about each row (not able to connect with id). Can someone guide me how can I do this? -
Django: Pass data from template button click to views.py and update template
How can I pass data from my template to views.py and update template with new context data. Preferable a clean update without refreshing the browser would be preferable, but refreshing the site would also be ok. Hope you can help. home.html: <body> <div> <button id="lemon" onclick="passFruit(this)" name="lemon">Lemon</button> <button id="Apple" onclick="passFruit(this)" name="Apple">Apple</button> <button id="Orange" onclick="passFruit(this)" name="Orange">Orange</button> </div> <p>Fruit is: {{ fruit }}</p> </body> <script> function passFruit(fruit) { // Pass fruit to views.py } </script> views.py: class home(TemplateView): template_name = 'home.html' // Get data here from template def get_context_data(self, **kwargs): context = super(home, self).get_context_data(**kwargs) // Update data here and return new context context["fruit"] = fruit return context -
How to persist data when no file is selected with django?
I have a form and I can uplaod a file and return the data of that file. But how to persist the data from the uploaded file when a user has not selected a file and triggers the upload function. What I mean with that is when the data is returned and a user will select again the upload function without selected a file then the returned data will be erased. this is the template: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{form}} <button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </div> </form> </div> </span> </div> </body> </html> {% endblock content %} and the views.py: def post(self, *args, **kwargs): filter_text = FilterText() types_of_encoding = ["utf8", "cp1252"] submitted_form = UploadFileForm(self.request.POST, self.request.FILES) content = '' if self.request.POST.get('form_pdf') is not … -
django import-export adding _x000D_ when importing content in RichTextField
I am using django-import-export library to handle import and export in my app. The problem is that in my body field I am using CKEditor RichTextField and every time I want to import the content from xlsx, yaml or json I see a lot of _x000D_ instead of empty lines. I've read in the documentation that I could use post_import signal to add some custom login when importing but I am not sure how to add regex that will delete all instances of _x000D_ from my content. How can I fix this issue? -
How to print all value with same name attribute in django and html?
I have django application. With form: <label for="new_chapther" class="plus_crapther_sign">New chapther</label> <button class="actual_plus" id="new_chapther" onclick="createNewChapther()">+</button> <form method="post"> {% csrf_token %} <br> <input type="text" placeholder="title"> <br> <input type="text" placeholder="description"> <br> <div id="chapter"></div> <br> <button type="submit">Submit</button> </form> When I click new chapter button, I trigger createNewChapter function in javascirpt: chapters = 0 function createNewChapther(){ if (chapters >= 100){ } else{ let chapter = document.getElementById('chapter') chapter.innerHTML += ` <br> <div class="added_chapter"> <input type="text" placeholder="chapter title" name="chapter_title"> </div> ` } chapters += 1 } This function adds content in chapter div. I can repeat that 100 times. You see I gave name attribute chapter_title to input. When I click submit in this html form, my view comes into play: def create_chapter(request): if request.method == 'POST': chapter_titles = request.POST.get('chapter_title') for t in chapter_titles: print(t) return render(request, 'quiz_create_form.html') In this view, I get chapter_titles with request.POST.get method. I want to print all value of input with name="chapter_title" in terminal, but when I run this it prints every letter in new line and only takes letters from last input with that name. How can I fix that and get all values printed in terminal? -
How i make api for terms and condition in python?
i have to send terms and conditions data to the user in mobile application but i dont know how to make the models structure for terms and condition in python i try tiny to post the data with the help of tiny editor -
Azure redis cache and Django setup
Am using django-redis in Django to add Azure redis cache, but I am getting issues with the connection, I added the keys password and the hostname and the port but no luck , I get this error : django_redis.exceptions.ConnectionInterrupted: Redis ConnectionError: Error while reading from myhostname.net:6380 : (104, 'Connection reset by peer') I tried reading existing answers but no luck. This is what I have in my Django settings.py : CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.getenv('REDIS_URL'), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", 'SSL': True, "PASSWORD": os.getenv('REDIS_PASSWORD'), } } } Where REDIS_URL is like this : REDIS_URL=rediss://myhostname.net:6380 and as well as REDIS_PASSWORD the password provided. What could I be missing, am testing this on Digitalocean, I have an SSL activated. -
making auto field Django in certain format in model.py
I'm trying to make auto field like that for invoice which is either part of customers table or invoice table it is okay in the 2 sitautions the format I want like this Year-Month-auto depends on the number before it for example : 202201-001 the first one , 202205-504 like that and it's auto generted once I create new customer model.py class enquiry(models.Model): enq_id = models.AutoField(auto_created = True, primary_key=True) name = models.CharField(max_length=100) Parent_name = models.CharField(max_length=100) Phone1 = models.IntegerField(unique=True) Phone2 = models.IntegerField() email = models.EmailField() place = models.CharField(max_length=50) DOB = models.DateField() # age = models.IntegerField(null=True) def __str__(self): return self.name I'm trying to make full auto id for my invoices so I can use in my view -
Django viewflow running queries in a custom node
I am trying to adapt the Viewflow Dynamicsplit example The objective is to split approvals of an Order based on OrderLines and to assign them to the appropriate approver. It seems that this should be possible as there seems to be a possibility described in this answer - Assign user to tasks automatically (Viewflow, Django) The issue is that whenever I try to grab the current order pk in the DynamicSplitActivation - the queryset comes back empty. Not sure where I am going wrong. The queryset works fine if I set the pk manually, but as soon as I try to use a dynamic variable it stops working. I have listed the flow and models etc. at the end of the post, however, I am guessing the issue is quite basic. Any help would be appreciated! nodes.py ... class DynamicSplitActivation(AbstractGateActivation): def calculate_next(self): self._order = self.flow_task._order_callback(self.process) order_id = self._order.pk # order_id = 28 order_lines = models.OrderLine.objects.filter(order_id=order_id) project_lines = project_models.ProjectLine.objects.filter(orderline__in=order_lines) users = User.objects.filter(projectline__in=project_lines).distinct() self._approvers = users ... class DynamicSplit(...): ... def __init__(self, callback): super(DynamicSplit, self).__init__() self._order_callback = callback self._ifnone_next_node = None ... flows.py ... approval_split = ( nodes.DynamicSplit(lambda act: act.order) .IfNone(this.end) .Next(this.split_approval_budget) ) models.py ... class ProjectLine(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) description … -
Django Sites Framework __str__ representation
I'm experimenting with the Django Site framework. In an UpdateView form, the Site model _str_ representation is self.domain, but I want to use self.name. For example, instead of 'www.test.com', I'd like 'Test, Inc.' to appear. I guess I could change the Django Site model code itself (shown below), but I don't really want to do that. I'd rather overwrite the setting in my app or the form view, but I can't figure out how to do either. class Site(models.Model): domain = models.CharField( _('domain name'), max_length=100, validators=[_simple_domain_name_validator], unique=True, ) name = models.CharField(_('display name'), max_length=50) objects = SiteManager() class Meta: db_table = 'django_site' verbose_name = _('site') verbose_name_plural = _('sites') ordering = ['domain'] def __str__(self): return self.domain def natural_key(self): return (self.domain,) When I subclass the Site model, my CustomSite tries to do a join with the Site model and causes complications, so it seems like that approach isn't ideal. class CustomSite(Site): objects = SiteManager() def __str__(self): return self.name class Meta: db_table = 'django_customsite' A simplified version of the form I was testing with is below. The form works. It updates the object with the right site, but I'd still like to know how to use the name as the representation instead of the … -
from sql to Django... i don't understand
i have 3 models (protocollo_pratica, protocollo_soggetto and protocollo_anaprat) and i need extract for each protocollo_pratica a list of soggetti with a specific "tipo" but i don't understand how to make this in django views. Thank you so much for your help. ` this is my models.py : ` from django.db import models # Create your models here. class Soggetto(models.Model): cognome = models.CharField(max_length=100, null=True) nome = models.CharField(max_length=100, null=True) comune_nascita = models.CharField(max_length=100, null=True) data_nascita = models.DateField(null=True) codice_fiscale = models.CharField(max_length=16, null=True) def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return self.nome class Pratica(models.Model): oggetto = models.CharField(max_length=100) anagrafe = models.ManyToManyField(Soggetto, through='Anaprat', through_fields=('pratica', 'soggetto'),) def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return self.oggetto class Anaprat(models.Model): tipo=models.CharField( max_length=50) pratica=models.ForeignKey("Pratica", related_name='pratiche', on_delete=models.CASCADE) soggetto=models.ForeignKey("Soggetto", related_name='soggetti', on_delete=models.CASCADE) def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return f"{self.tipo, self.soggetto}"` and this is my sql query : `SELECT p.id, pa.tipo tipo, ps.cognome, ps.nome, ps.data_nascita, ps.comune_nascita from (SELECT id id from protocollo_pratica pp ) p, protocollo_anaprat pa left JOIN protocollo_soggetto ps on ps.id=pa.soggetto_id where p.id=pa.pratica_id` -
Postgresql database throwing errors on connection
I am running a Postgresql database on AWS and the backend is Django. After some requests, let's say 50, it raises the error "OperationalError: terminating connection due to administrator command SSL connection has been closed unexpectedly" but the database will still remain active. At first, it was throwing "OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections" after some requests, so I have a script that closes open connections. Here is the script: export PGPASSWORD='mypassword' psql --host=dbhost.myregion.rds.amazonaws.com --port=5432 --username=user --dbname=name \ -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid <> pg_backend_pid() AND state in ('idle', 'idle in transaction', 'idle in transaction (aborted)', 'disabled') AND usename != 'rdsadmin';" but the errors keep coming. I have also tried increasing the max_connections to 150, but it still doesn't help. I have also tried using AWS RDS proxy, but still no hope. Here is how I connect to the DB from django: DATABASES = { 'default': { 'ENGINE': config('DB_ENGINE'), 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': config('DB_PORT'), 'CONN_MAX_AGE': 0 } } -
Drf class based view how to manage method calls
I have been working on FBV in Django and am now trying out CBV. I have created a basic crud application Views.py class UserViews(APIView): permission_classes = [IsViewOnly | IsManager | IsAdmin | IsStaff] def get_objects(self, user_id): #query def post(self, request): #create code def get(self, request): #details code def put(self, request): #update code def delete(self): #code urls.py urlpatterns = [ path('add-user/', views.UserViews.as_view(), name="create-user"), path('update-user/', views.UserViews.as_view(), name="update-user"), path('delete-user/', views.UserViews.as_view(), name="delete-user"), path('list-users', views.UserSearchList.as_view(), name="list-user"), path('view-user', views.UserViews.as_view(), name="view-user"),] This code is working but, how do we prevent a situation where say a manager wants the view user details API but executes it with the delete method and the user is now deleted -
how can I update one field in Django rest framework in abstract user model
how can I update one field in the Django rest framework in the abstract user model can someone help me I want to Update device_id in my abstract user model I want to only update device_id dield without updating other field and I do not know I have to create another view or not or I should add update to serializers here is my code models.py class User(AbstractUser): is_student=models.BooleanField(default=False) is_teacher=models.BooleanField(default=False) mobile_no=models.CharField(max_length=200,blank=True) device_id=models.CharField(max_length=200,blank=True) USERNAME_FIELD = 'username' def __str__(self): return self.username class Meta: verbose_name_plural="1.User" @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False,**kwargs): if created: Token.objects.create(user=instance) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model=User fields=['id','username','mobile_no','is_student','device_id'] views.py class StudentSignupView(generics.GenericAPIView): serializer_class=StudentSignupSerializer def post(self,request,*args,**kwargs): serializer=self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user=serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": Token.objects.get(user=user).key, # "message":"account created successfully" }) class TeacherSignupView(generics.GenericAPIView): serializer_class=TeacherSignupSerializer def post(self,request,*args,**kwargs): serializer=self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user=serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": Token.objects.get(user=user).key, # "message":"account created successfully" }) class CustomAuthToken(ObtainAuthToken): def post(self,request,*args,**kwargs): serializer=self.serializer_class(data=request.data, context={'request':request}) serializer.is_valid(raise_exception=True) user=serializer.validated_data['user'] token,created=Token.objects.get_or_create(user=user) return Response({ 'token':token.key, 'user':UserSerializer(user, context=self.get_serializer_context()).data, 'is_student':user.is_student }) -
Need for installing a server for django app deployment on various hosting sites
On finishing with a django site, do I need to install for e.g nginx and uwsgi before uploading it to heroku or pythonanywhere? If no, does it mean heroku or pythonanywhere provides the server for me? And which places do not provide the server and I therefore need to install nginx and uwsgi or gunicorn. What are the differences between those that provide the server and those that don't? Which is good? -
How to retrieve the docker image of a deployment on heroku via circleci
I have a django application running locally and i've set up the project on CircleCi with python and postgres images. If I understand correctly what is happening, CircleCi would use the images to build a container to test my application with code database. Then I'm using the job heroku/deploy-via-git to deploy it to Heroku when the tests are passed. Now I think Heroku is using some images too to run the application. I would like to get the image used by heroku to run my site locally on another machine. So pull the image then push it to Docker Hub and finally download it back to my computer to only have to use a docker compose up. Here is my CircleCi configuration's file version: 2.1 docker-auth: &docker-auth auth: username: $DOCKERHUB_USERNAME password: $DOCKERHUB_PASSWORD orbs: python: circleci/python@1.5.0 heroku: circleci/heroku@0.0.10 jobs: build-and-test: docker: - image: cimg/python:3.10.2 - image: cimg/postgres:14.1 environment: POSTGRES_USER: theophile steps: - checkout - run: command: pip install -r requirements.txt name: Install Deps - run: name: Run MIGRATE command: python manage.py migrate - run: name: Run loaddata from Json command: python manage.py loaddata datadump.json - run: name: Run tests command: pytest workflows: heroku_deploy: jobs: - build-and-test - heroku/deploy-via-git: requires: - build-and-test … -
I want only users who don't have inactive comments to post new comments
Comment matching query does not exist. inactive_comments = Comment.objects.get(active=False, profile=profile) This is my view: def post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day) tags = Tag.objects.all() tagsList = [] for tag in post.tags.get_queryset(): tagsList.append(tag.name) profile = Profile.objects.get(user=request.user) inactive_comments = Comment.objects.get(active=False, profile=profile) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.profile = profile new_comment.post = post new_comment.save() return HttpResponseRedirect(request.path_info) else: comment_form = CommentForm() post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:3] return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts, 'tagsList': tagsList, 'tags': tags, 'inactive_comments': inactive_comments}) This is my comment models: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_comments') body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) and this is my template: {% if request.user.is_authenticated %} <div class="new_comment"> {% if inactive_comments %} <h4>نظر شما با موفقیت ثبت شد و در حال بررسی است.</h4> {% else %} <h4>نظر خود را اضافه کنید</h4></br> <form method="post"> <div class="row" dir="rtl"> <div class="col-sm-12 col-md-8"> {{ comment_form.body|attr:"class:form-control"|attr:"type:text" }} </div> </div> {% csrf_token %} <div class="row"><br/> <div class="col-sm-12 col-md-8"> <input type="submit" value="ارسال نظر" class="btn send btn-primary" href="#"></input> </div> …