Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make a select tag work in django a?
So i have been working on a project that pull user github API and I already success pull it to my project but I dont know how to do the select part to seperate the value. Here is the photo from my page: and here is my views.py: def user(req, username): username = str.lower(username) # Get User Repo Info with urlopen(f'https://api.github.com/users/{username}/repos') as response: source = response.read() user_repos = json.loads(source) def sort_user_repo_by_stars(user_repos): return user_repos['stargazers_count'] user_repos.sort(key=sort_user_repo_by_stars, reverse=True) created_at = data['created_at'] created_at = datetime.datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%SZ") created_at = created_at.strftime("%B %d, %Y") context = { 'username': username, 'data': data, 'created_at': created_at, 'limit_data': limit_data, 'user_repos': user_repos[:8], } return render(req, 'user.html', context) and here is my template user.html: <div class="repo-info"> {% for repo in user_repos %} <div class="card-deck"> <div class="card shadow"> <div class="card-body"> <h4 class="card-title" style="font-family: 'Space Mono', monospace;"> {{repo.name}}</h4> <p class="card-text clearfix"> <i class="fas fa-circle"></i> {% if repo.language %} <span> {{repo.language}}</span> {% endif %} <i class="fas fa-star"></i> {{repo.stargazers_count}} <i class="fal fa-code-branch"></i> {{repo.forks}} {% load humanize %} <span class="float-right">{{repo.size|intcomma}} KB</span> </p> </div> </div> </div> {% endfor %} </div> So I already did the repos that sorted by stars and now I want to do it with sorted by folks and sorted by size and when I click … -
Import hashed password from flask to django
I have to migrate my flask Users to django. In flask I generated the password with the werkzeug lib like: generate_password_hash(value, method='sha256') In the django import I save the password: u.password = hashed_pw now the password is in the database like: 'sha256$VSvtvATP$2c87cf...' now django can't verify my password. How can I convert the password so that django can handle it? -
Django server cache select statement in Postgres DB
I have a select Django statement like this: import datetime from django.db.models import Count, Q from mobileapp.models import * import math from functools import partial from django.utils import timezone from mobileapp.decorators import logging__time date=timezone.now() first = date.replace(day=1) last_month = first - datetime.timedelta(days=1) subsidiaries = Subsidiary.objects.select_related('frequency').select_related('last_call').filter(user=user).annotate(number_of_calls=Count('calls', filter=Q(calls__start__gte=last_month, calls__start__date__lte=date))) Even though today date is 6.30. the query in the logs look like this: SELECT "mobileapp_subsidiary"."id", "mobileapp_subsidiary"."subsidiary_ref", "mobileapp_subsidiary"."name", "mobileapp_subsidiary"."address", "mobileapp_subsidiary"."city", "mobileapp_subsidiary"."coordinates_x", "mobileapp_subsidiary"."coordinates_y", "mobileapp_subsidiary"."phone_number", "mobileapp_subsidiary"."frequency_id", "mobileapp_subsidiary"."channel", "mobileapp_subsidiary"."subchannel", "mobileapp_subsidiary"."user_id", "mobileapp_subsidiary"."day_planned", "mobileapp_subsidiary"."customer_id", "mobileapp_subsidiary"."last_call_id", COUNT("mobileapp_calls"."id") FILTER ( WHERE (("mobileapp_calls"."start" AT TIME ZONE 'Europe/Ljubljana')::date <= '2020-06-11'::date AND "mobileapp_calls"."start" >= '2020-05-31T08:01:06.244114+00:00'::timestamptz)) AS "number_of_calls", "mobileapp_frequency"."name", "mobileapp_frequency"."calls_per_month", T5."id", T5."start", T5."end", T5."notes", T5."type", T5."user_id", T5."subsidiary_id", T5."order_id" FROM "mobileapp_subsidiary" LEFT OUTER JOIN "mobileapp_calls" ON ("mobileapp_subsidiary"."id" = "mobileapp_calls"."subsidiary_id") LEFT OUTER JOIN "mobileapp_frequency" ON ("mobileapp_subsidiary"."frequency_id" = "mobileapp_frequency"."name") LEFT OUTER JOIN "mobileapp_calls" T5 ON ("mobileapp_subsidiary"."last_call_id" = T5."id") WHERE "mobileapp_subsidiary"."user_id" = 2 GROUP BY "mobileapp_subsidiary"."id", "mobileapp_frequency"."name", T5."id"; args=(datetime.date(2020, 6, 11), datetime.datetime(2020, 5, 31, 8, 1, 6, 244114, tzinfo=<UTC>), 2); I check the later logs and it is always query for 6.11 (even for previous days). It looks like the query is cached somehow and called the same query every time, even that date is changed... if I use Django-extensions shell and I run the function from there, … -
How to provide default list for ArrrayField in Django
I am using ArrayField for my item's statistics. This array contains things like items views, button clicks, etc. Now, problem is I am unable to set default value [0,0,0] when a new item is created. Which is the best way to give default 0 values for all ArrayField elements? item_stats = ArrayField(base_field=models.PositiveIntegerField(default=0), size=3, default=list) Currently, I am getting this field is required because default is empty-list( [] ) Thanks -
Django tabular inline is very slow
I found an admin page with a tabular inline is very slow. The inline widget has 20 lines and each line has 15 fields. I got this result with debug toolbar. It takes Total: 81121.01ms while sql only takes 177 queries in 1709.65ms. Render template consumes most of time, and if I remove {{field.field}} in tabular.html, the page takes less than 2000ms. So how can I improve it? -
Custom template tag to check user matches record in span relationship
I am trying to make a template tag to check if the current logged in user matches a field in a record, the field being, foreign key relationship to a Django user model. I wanted to do this in a template just so it's easy to display an error message if a user tries accessing a record for which they are not assigned. My models are: class Client(models.Model): client_email = models.EmailField(max_length = 254) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) phone = PhoneField(blank=True) assigned_manager = models.ForeignKey(Manager, on_delete=models.CASCADE, blank=True, null=True) created_date = models.DateTimeField(default=timezone.now) class Manager(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) manager_email = models.EmailField(max_length = 254) username = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) This is my attempt at a custom template tag, which I know is wrong but I'm not sure wht the correct approach would be. I would appreciate some hints or a pointer in the right direction. register = template.Library() @register.filter(name='check_assigned') def check_assigned(user): try: assigned_manager = Client.objects.get(manager__username=user) except Object.DoesNotExist: return False return assigned_manager -
payu web-hooks failed due to django referer check
I am integrating payu web-hooks on my django project . there are total four callbacks events from payu side i.e. success , dispute , failure and refund . Each callback is sending POST request to the django backend . The problem is occurring when i handle any callback event , django requires the csrf token which is missing inside payu request body so i added @csrf_exempt to bypass it and it worked , but after two or three requests , django starts to reject with the error message called 'Forbidden (Referer checking failed - no Referer.): /payu/success/' After a bit of research i found that there is something called csrf-trusted-origins in django where i can add payu origins ... but unfortunately i didn't any help here too . any help will be appreciated ... thanks . -
Inheriting multiple abstract classes in Django
I have two Abstract base classes A and B which both inherit from models.Model. Now I need to have concrete class C to inherit from A and B. I read that in the accepted answer of another question that it's not recommended to inherit from two abstract classes that both inherit from models.Model. I tried looking up for solutions to get around that but found nothing suitable. Could someone please provide a suggestion how to or if it's okay to inherit from A and B? -
Does the installation of same packages for two different python projects in two virtual environment result in wastage of memory?
I was working on a Django project and got a doubt that if we have two projects running in our system say P1 and P2 and both has its own venv as V1 and V2. At some point of time both project requires same python packages and I if am to install that package twice in my system result in wastage of space? If so what is the use of virtual environment? Only to run projects in isolated environments? Please can anyone tell me? -
Unable to insert image in excel sheet using xlwt Django
while i creating an api.I have added images in my model ,and want to export to excel sheet.In the excel file i am downloading images are not showing: #models class Task(models.Model): Id=models.IntegerField() Name=models.CharField(max_length=50,null=False,blank=True) Image1=models.FileField(blank=True, default="", upload_to="media/images",null=True) Image2=models.FileField(blank=True, default="", upload_to="media/images",null=True) Date=models.DateField(null=True,blank=True) def __str__(self): return str(self.Name) #viewset class TaskViewSet(viewsets.ViewSet): def list(self, request): try: response=HttpResponse(content_type='application/ms-excel') response['Content-Disposition']='attachment; filename="users.xls"' wb=xlwt.Workbook(encoding='utf-8') ws=wb.add_sheet('Tasks') row_num=0 font_style=xlwt.XFStyle() font_style.font.bold=True columns=['Id','Name','Image1','Image2','Date'] for col_num in range(len(columns)): ws.write(row_num,col_num,columns[col_num],font_style) font_style=xlwt.XFStyle() data=Task.objects.all()#.values_list('Id','Name','Image1','Image2','Date') for my_row in data: row_num+=1 ws.write(row_num,0,my_row.Id,font_style) ws.write(row_num,1,my_row.Name,font_style) #ws.write(row_num,2,my_row.Image1.url,font_style) ws.write(row_num,2,my_row.Image1.url,font_style) #ws.insert_bitmap(row_num,2,my_row.Image1.url,font_style) ws.write(row_num,3,my_row.Image2.url,font_style) #ws.insert_bitmap(row_num,3,my_row.Image2.url,font_style) ws.write(row_num,4,my_row.Date,font_style) wb.save(response) print(my_row.Date) return response except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) -
Django plain-text email template generates \n after template tags
Interesting issue here: I have plain-text emails sent by my Django app, with the following code: email_context = dict() email_context['to'] = user.display_name email_context['new'] = user_data['new'] email_context['for_reminder'] = user_data['for_reminder'] plaintext = get_template('email/notification.txt') text_content = plaintext.render_to_string(email_context) html = get_template('email/notification.html') html_content = html.render(email_context) email = EmailMultiAlternatives( subject='Assignments', body=text_content, to=[user.email], reply_to=[settings.DEFAULT_FROM_EMAIL], ) # email.attach_alternative(html_content, "text/html") email.send() the 'email/notification_base.txt' template looks like such: Dear {{ to }}, {% if new %} You have been assigned to the following NEW cases: {% block new %} {% endblock %} {% endif %} {% if for_reminder %} You still have the following previously assigned cases, which need your attention: {% block for_reminder %} {% endblock %} {% endif %} Thank you for your assistance. Sincerely, The Team the 'email/notification.txt' template just extends base. My problem with it is, that the email it generates and sends to the addressee, actually gets rendered with a NEWLINE in every spot where the template had {% something %} tags. This results in a very unevenly formatted email text. As an example, if both blocks were missing the email would look like: Dear Someone, Thank you for your assistance. Sincerely, The Team Are there any ways around this problem? -
Реализация уведомлений Django
Всем привет, пытаюсь реализовать пользовательский уведомления на Django. создал app сделал приблизительные модели u_notification models from django.db import models from users.models import Profile as User class Actions(models.Model): """ Это модель всех действий пользователей (создал пост\прокомментировал пост\ лайкнул пост и т д """ by_user = models.ForeignKey(User, on_delete=models.CASCADE) action = models.CharField(max_length=500) class Notifications(models.Model): """ Модель подписки на уведомление """ actions = models.OneToOneField(Actions, on_delete=models.CASCADE) to_users = models.ManyToManyField(User, null=True) создал пробный сигнал, когда комментируют пост юзера, чтобы ему приходило уведомление u_notification/signals from django.db.models.signals import post_save from django.dispatch import receiver from post.models import Post, Comments from .models import Actions, Notifications @receiver(post_save, sender=Comments) def new_post_listeners(sender, instance, **kwargs): message = f'{instance.author} comment post {instance.post.title}' action = Actions(by_user=instance.author, action=message) action.save() notification = Notifications(actions=action) notification .save() notification .to_users.add(instance.post.author) На данном этапе работает, но вопрос в том, как реализовать подписку на уведомления со стороны пользователя, и правильно ли я построил модель? Подобную информацию я искал но не нашел, помогите пожалуйста. -
how to use Google Classrom api in django?
I am new to Django and want to build a website. I want to use Google Classroom and monkey-learn API. Is there is any guide available? -
How to know the python packages versions used by other people's Django project and install them accordingly?
I was given a project containing a number of python files without documentation. I noticed the folder contains manage.py so I assume it's a Django project. I want to setup the environment and run it. However, it's hard to figure out the appropriate packages. For example, firstly I installed the latest version of deepctr 0.8.0. Then I want to run the project, it show the error: "ImportError: cannot import name 'SparseFeat' from 'deepctr.inputs'". After some research, I found it's the deepctr version issue. I downgraded to deepctr 0.7.0, and the error disappeared. Then a new error appeared: "RuntimeError: get_session is not available when using TensorFlow 2.0." Then following this issue's suggestion https://github.com/OlafenwaMoses/ImageAI/issues/367 , I downgraded to TensorFlow 1.13 Then this error disappeared but a new error appeared: "ValueError: ('Unrecognized keyword arguments:', dict_keys(['ragged']))". Then after looking at this issue https://github.com/tensorflow/tensorflow/issues/33479 it appears the tensorflow version should be 1.15. Then finally the project can run without errors. So I have to try different versions of python packages and search for error messages. Is there a way to know the python packages versions used by the Django project? -
how to only append new data in ajax request django?
hello guys so i have this ajax script that get the data from my backend view it works but it only empty the data and replace it with the new one but what i want to do is that i want this ajax request to only get the new data that is not in my div task if the data is in my div task i want to tell it to don't append it i try to do it here: def task_admin_manager(request): if request.is_ajax(): data_task = task_admin_form.objects.all() list_id_task = [] for data in data_task: data = data.id if data is not in list_id_task and task_admin_form.objects.filter(id__exact=data).exists(): id_fix = data_task.objects.filter(id__exact=data) list_id_task.append(id_fix) for id_task in id_fix: dict_id_task = {} dict_id_task['username'] = id_task.username.username return Httpresponse(json.dumps(dict_id_task)) because i used return it will only get one data because it will break the loop if i put the return outside the loop it will still print one data because the dict will keep appending the data with same key but different value, can someone give me a tips? or how they do it if the cases like this? thanks here is my code. def task_admin_manager(request): if request.is_ajax(): data_task = task_admin_form.objects.all() return render(request,"task_mager.html",{"form_task":dict_id_task}) task_mager.html {% load static %} … -
how when Superuser created successfully. ok but It is not made Superuser in table auth_user?
when python manage.py createsuperuser Superuser created successfully. ok but It is not made Superuser in table auth_user mysql> select * from auth_user; Empty set (0.00 sec) help me where the problem is Django==2.2.7 mysqlclient==1.4.6 mysql Ver 14.14 Distrib 5.7.30, for Linux (x86_64) using EditLine wrapper -
how to sort an array of object in django?
I am making an project with python and django about github profile. I already successful call user github API and it give me like a lot of repos from that user and I want to display like 8 of them and sorted by stars or forks or size of that repo. How can I do that? Here's an image of my page: Here is my views.py: def user(req, username): username = str.lower(username) # Get User Info with urlopen(f'https://api.github.com/users/{username}') as response: source = response.read() data = json.loads(source) # Get Limit Call API with urlopen(f'https://api.github.com/rate_limit') as response: source = response.read() limit_data = json.loads(source) # Get User Repo Info with urlopen(f'https://api.github.com/users/{username}/repos') as response: source = response.read() user_repos = json.loads(source) def sort_user_repo_by_stars(user_repos): return user_repos['stargazers_count'] user_repos.sort(key=sort_user_repo_by_stars, reverse=True) created_at = data['created_at'] created_at = datetime.datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%SZ") created_at = created_at.strftime("%B %d, %Y") context = { 'username': username, 'data': data, 'created_at': created_at, 'limit_data': limit_data, 'user_repos': user_repos, } return render(req, 'user.html', context) and here is my template user.html: <div class="repos"> <div class="top-repo"> <label for="top-repos" class="col-sm-3 col-form-label">Top Repos <span>by </span></label> <select class="custom-select bg-light text-primary" name="pick"> <option selected="stars">stars</option> <option value="forks">forks</option> <option value="size">size</option> </select> </div> <div class="repo-info"> {% for repo in user_repos %} <div class="card-deck"> <div class="card shadow"> <div class="card-body"> <h4 class="card-title">{{repo.name}}</h4> <p … -
Django - Field by Field Restrictions on Which Users Can view Certain Fields
I'm learning Django and building a simple CRUD application. I have a model for cars, and this contains a number of fields. When a user loads a car page, I'd like some fields to be displayed and others hidden, depending on whether the user has a high enough score for the car they are viewing. So for each field (engine, wheels, headlights, etc), or for some groups of fields, there would be a corresponding visibility score. If the user's score for that particular car exceeded the visibility for a particular field, then the data for that field would be displayed in the view. I could add a DecimalField variable for each component to denote this minimum score, the Car model would have a calc_score(user) method. In the view the current user's score would be compared against each of these, but I'm guessing there may be a better way to do this. Can anyone recommend a better approach? Thank you. -
Django Admin Ask a User a List of Questions
I am trying to create a custom admin page for new staff members. I have the following 4 models (fields in parenthesis) -User (id, first_name, last_name) -Question (id, question_text, answerchoices_id, date_created) -AnswerChoices (id, choice_text) -M2M thru model (id, user_id, question_id, answerchoice_id) I want to create an admin change form / view that lets a user edit their User info + get presented a list of the last 5 multiple choice questions (date_created) with choices as a radio select. I need all 5 questions to be shown at once (whether an M2M exists yet or not). If a user already answered the question before, I want the answer to be prefilled based on the existing M2M values. I have identified it as a user model admin page with an inline for the M2M model. I’m not sure how to force display the last 5 questions all at once, or how to render the question_text and choice_text. Thank you for your help! -
With Django, how do I reference an existing model in a form save method instead of creating a new instance?
I'm trying to use a ModelChoiceField to display options populated from model, and when a user selects a choice, store that method in a different model. I'm using a standard form instead of a ModelForm, because I wasn't able to get the form to display how I wanted to when using a Modelform. My issue is that in my form save method, a new instance is created, which is not what I want. Here are the relevant models: class Client(models.Model): client_email = models.EmailField(max_length = 254) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) phone = PhoneField(blank=True) assigned_manager = models.ForeignKey(Manager, on_delete=models.CASCADE, blank=True, null=True) created_date = models.DateTimeField(default=timezone.now) @property def full_name(self): return '{0} {1}'.format(self.first_name, self.last_name) class Manager(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) manager_email = models.EmailField(max_length = 254) username = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) @property def full_name(self): return '{0} {1}'.format(self.first_name, self.last_name) My view: def manageclient(request, urlid): client = Client.objects.get(id=urlid) form = AssignManagerForm() if request.method == "POST": form = AssignManagerForm(request.POST) if form.is_valid(): form.save() return render(request, 'mysite/manageclient.html', {}) else: form = AssignManagerForm() context = { 'client': client, 'urlid': urlid, 'form': form, } return render(request, 'mysite/manageclient.html', context) And my forms.py class AssignManagerForm(forms.Form): full_name = forms.ModelChoiceField(queryset=Client.objects.all()) def save(self): data = self.cleaned_data client = Client(assigned_manager=data['full_name']) client.save() What I need to … -
Reverse for 'finished' with arguments '('',)' not found. 1 pattern(s) tried: ['finished/(?P<task_id>[^/]+)$']
I have tried various patterns of solutions but for some reason they don't work. Below I attached the pieces of code that I think are contributing to the error models.py from django.db import models from django.utils import timezone # Create your models here. class task(models.Model): title = models.CharField(max_length = 40) category = models.CharField(max_length = 20) description = models.CharField(max_length = 100) date = models.DateField(default = timezone.now) finished = models.BooleanField(default = False) def __str__(self): return self.title views.py @require_POST def addToDO(request): form = taskForm(request.POST) if form.is_valid(): items = task(title = request.POST['title'], category = request.POST['category'], description = request.POST['description']) items.save() return redirect('main') def completedToDO(request, task_id): items = task.objects.get(pk = task_id) items.finished = True items.save() return redirect('main') urls.py from django.urls import path from . import views urlpatterns = [ path('', views.main, name = 'main'), path('add', views.addToDO, name = 'add'), path('finished/<task_id>', views.completedToDO, name = 'finished'), ] list.html <ul class="list-group"> <a href = "{% url 'finished' task_id %}" onMouseOver = "style.transform='scale(1.1,1.1)'" onMouseOut = "style.transform='scale(1,1)'" ><li class="list-group-item"> {{ items.title }} <b> {{ items.category }} </b> <br> {{ items.description }} <br> <hr> {{ items.date }}</li></a> </ul> -
How to do a whatsapp push notification when user submits a form in my application
I am making a web application in Django for sales and feedback for my services and for that I need to communicate with my customers as soon as they fill the form , on Whatsapp .So i go about like this : customers fill the form and submit the data and i have to check the admin pannel or database every once in a while for customer's contact , then i individually retrieve the contacts one by one and enquire them. How do i implement push notification of the contacts directly on Whatsapp so that whenever a user submits the form i get a notification on Whatsapp and i communicate with them easily, please help it would save me from a lot of trouble.ThankYou for your time. Here is the code snippet: **#models.py** from django.db import models class detail(models.Model): name = models.CharField(max_length=120) email = models.EmailField(max_length=120) mob = models.BigIntegerField(primary_key='True') age = models.IntegerField() **#views.py** def jobs(request): if request.method=='POST': name=request.POST.get('name') email=request.POST.get('email') mob=request.POST.get('mob') age=request.POST.get('age') detail_obj=detail(name=name,email=email,mob=mob,age=age) detail_obj.save() return render(request,"home_page.html",{"message":"Thank You we will Reach out to you shortly"}) -
php preg_replace in python
i have a php function that clean any special character and now i want to create a function like php in python my php function: function cleanString($text) { $utf8 = array( '/[áàâãªä]/u' => 'a', '/[ÁÀÂÃÄ]/u' => 'A', '/[ÍÌÎÏ]/u' => 'I', '/[íìîï]/u' => 'i', '/[éèêë]/u' => 'e', '/[ÉÈÊË]/u' => 'E', '/[óòôõºö]/u' => 'o', '/[ÓÒÔÕÖ]/u' => 'O', '/[úùûü]/u' => 'u', '/[ÚÙÛÜ]/u' => 'U', '/ç/' => 'c', '/Ç/' => 'C', '/ñ/' => 'n', '/Ñ/' => 'N', '/–/' => '-', // UTF-8 hyphen to "normal" hyphen '/[’‘‹›‚]/u' => ' ', // Literally a single quote '/[“”«»„]/u' => ' ', // Double quote '/ /' => ' ', // nonbreaking space (equiv. to 0x160) ); return preg_replace(array_keys($utf8), array_values($utf8), trim($text)); } i've tried in python like below: def clean(text): utf8 = { '/[áàâãªä]/u' : 'a', '/[ÁÀÂÃÄ]/u' : 'A', '/[ÍÌÎÏ]/u' : 'I', '/[íìîï]/u' : 'i', '/[éèêë]/u' : 'e', '/[ÉÈÊË]/u' : 'E', '/[óòôõºö]/u' : 'o', '/[ÓÒÔÕÖ]/u' : 'O', '/[úùûü]/u' : 'u', '/[ÚÙÛÜ]/u' : 'U', '/ç/' : 'c', '/Ç/' : 'C', '/ñ/' : 'n', '/Ñ/' : 'N', '/–/' : '-', # UTF-8 hyphen to "normal" hyphen '/[’‘‹›‚]/u' : ' ', # Literally a single quote '/[“”«»„]/u' : ' ', # Double quote '/ /' : ' ', # nonbreaking … -
Adding a new function to count comments in a Class based view
I am trying to get the count of comments in my comment section I have added this function to the models to get the count, I am getting 'ItemDetailView' object has no attribute 'comment' error class Comment(models.Model): STATUS = ( ('New', 'New'), ('True', 'True'), ('False', 'False'), ) item = models.ForeignKey(Item, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ItemComments") comment = models.CharField(max_length=250, blank=True) status = models.CharField(max_length=10, choices=STATUS, default='New') def __str__(self): return '{} by {}'.format(self.subject, str(self.user.username)) def total_comments(self): return self.comment.count() I have also included it in the views which i think might be the reason for not working properly class ItemDetailView(DetailView): model = Item template_name = "product.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["comments"] = Comment.objects.filter(item=self.object, status='New') total_comments = self.comment.total_comments() context["total_comments"] = total_comments return context Here is the template <h5><span>{{ total_comments }}</span> review for <span>{{object.title|capfirst }}</span></h5> Thank you -
Best option to use Celery to run one command behind the other
I have an app made in django in which at some point the user uploads a file, it is sent to another server and a couple of scripts are executed. As this is a fairly slow process (it can take up to 10 minutes) i decided to pass the execution of this process to celery, which i configured with redis (because rabbitmq sometimes gave some disconnection problems). One of the requirements for this whole process to work is to send the file to the server/execute the scripts one at a time, i mean, if two users upload a file at the same time, they can't run in parallel, one needs to be executed first and then the other I managed to do this with this command celery -A my_app worker -B -l info --concurrency=1 --scheduler django_celery_beat.schedulers:DatabaseScheduler But i don't know how reliable is this approach, it is possible for this way of executing Celery to have anything to do with celery some times not taking the tasks? its like sometimes i execute the fuction to call the task and nothing happens