Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get username in django_requestlogging
I am using ‘django_requestlogging’ for the log file and I have followed django_requestlogging this link and configured it as per the steps given. I am not getting the username in the log file instead of that I am getting “-”. Please find the code details. step1.Installed application INSTALLED_APPS = [ ------- ------ 'django_requestlogging', ] step2: Created Middleware from django.utils.deprecation import MiddlewareMixin from django_requestlogging.middleware import LogSetupMiddleware as Original class LogSetupMiddleware(MiddlewareMixin, Original): pass step3: used in settings.py MIDDLEWARE = [ ‘django.middleware.security.SecurityMiddleware’, ‘django.contrib.sessions.middleware.SessionMiddleware’, ‘django.middleware.common.CommonMiddleware’, ‘django.middleware.csrf.CsrfViewMiddleware’, ‘django.contrib.auth.middleware.AuthenticationMiddleware’, ‘django.contrib.messages.middleware.MessageMiddleware’, ‘django.middleware.clickjacking.XFrameOptionsMiddleware’, ‘user_visit.middleware.UserVisitMiddleware’, # ‘django_requestlogging.middleware.LogSetupMiddleware’, ‘apple.middleware1.LogSetupMiddleware’ ] step4: Configuration import logging import logging.config LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, 'filters': { # Add an unbound RequestFilter. 'request': { '()': 'django_requestlogging.logging_filters.RequestFilter', }, }, 'formatters': { 'request_format': { 'format': '%(remote_addr)s "%(request_method)s ' '%(path_info)s %(server_protocol)s" %(http_user_agent)s ' '%(message)s %(asctime)s', }, 'simple': { 'format': '[%(asctime)s] - %(levelname)5s -:%(message)3s -" %(username)5s' }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'filters': ['request'], 'formatter': 'simple', }, 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'Apple00012.log', 'formatter':'simple' }, }, 'loggers': { 'django': { # Add your handlers that have the unbound request filter 'handlers': ['console','file'], 'level': 'DEBUG', 'propagate': True, # Optionally, add the unbound request filter to your # … -
What is the best way to set up a daemon process in django
I am working on an exchange related program that matches buy and sell orders from clients. I am new to django and I am trying to figure out the best way to implement my logic. Suppose I have a coroutine that accepts a stream of client generated data like so: @coroutine #primes coroutine def waiter(q): """ Accepts orders from clients, sorts and puts them in a processing queue """ sell_orders = [] buy_orders = [] while True: size, price, order = yield orderq = sell_orders if order == "sell" else buy_orders orderq.append((size, price, order)) orderq.sort(key = lambda x: x[0], x[1]) #can this be done in redis? q.put(sellOrders[0], buyOrders[0]) And suppose I have a daemon process that checks the queue and processes the data like so: def chef(q): """ Daemon process, checks queue for orders Match orders when buy price is > than sell price """ sleep = 5 while True: if not q.empty(): buy, sell = q.get() buy_price, sell_price = buy[0], sell[0] if buy_price >= sell_price: print("Make Trade") else: time.sleep(sleep) q = Queue(maxsize=0) t = Thread(target = chef, args =(q,) ) t.setDaemon(True) t.start() I can pass orders to the waiters like so: if __name__ == '__main__': m = Waiter(q) buy … -
Django 3.1.4 - AUTH_USER_MODEL refers to model 'users.AppUser' that has not been installed even though app is in INSTALLED_APPS
I've encountered a very odd issue, that I'm suspecting I'll have to put in an issue for with the django team. I've followed the documentation here to great success at setting the following custom user model: apps.users.models.py ... # Here, the genders choices are declared in models.py class Genders(models.TextChoices): UNSPECIFIED = '', _('Unspecified') MALE = 'M', _('Male') FEMALE = 'F', _('Female') # Create your models here. class AppUser(AbstractUser): gender = models.CharField( max_length=6, choices=Genders.choices, default=Genders.UNSPECIFIED, blank=True) birthday = models.DateField(blank=True, null=True) weight = models.DecimalField( max_digits=5, decimal_places=2, null=True, blank=True) @property def age(self): return relativedelta(date.today(), self.birthday).years if self.birthday else None def get_eligable_age_divisions(self) -> 'QuerySet[WeightClass]': query = self.__get_bound_query(self.age) # TODO Genders being in the user models module is causing a circular reference. # move genders to separate module caused the appUser module to appear as not registered # pylint: disable=import-outside-toplevel from apps.divisions.models import AgeDivision return AgeDivision.objects.filter(query) ... apps.divisions.models ... class WeightClass(models.Model): gender = models.CharField( max_length=1, blank=True, choices=Genders.choices, default=Genders.UNSPECIFIED) lower_bound = models.PositiveIntegerField(default=0) upper_bound = models.PositiveIntegerField(default=0) ... settings.py ... INSTALLED_APPS = [ 'apps.users', 'apps.divisions', ... ] AUTH_USER_MODEL = 'users.AppUser' ... The above works with no issues. However, I really don't like my imports anywhere but at the top level, as it adds unnecessary confusion about module dependencies. … -
Django 3 takes only django.po file into consideration: normal?
Django 3 under Windows10 in development environment. A single Django app. Generation of .po file and compilation into .mo files working well. The default filename is django.po. But translation works fine only if translation file is django.mo (compiled from django.po) If filename is changed - I wanted to give it the app name so my_app.po - the compilation works, but the translation process ignores it. I tried with two .po files, one named django.po and the other one my_app.po. Compilation of both is fine, but the translation process only take into account django.mo. If I remove both mo files, switch names (django to my_app and vice-versa), compile to .mo and try, only the new django.mo is taken into account. If none of them is django.po, both are ignored. So only django.mo file (always compile po file(s) so .mo match .po filename) is taken into account. Is there any reason ? Is it possible to modify that behavior ? -
Gunicorn doesn't respond on Heroku
I run a gunicorn server on Heroku with the Django framework, but it doesn't respond and closes a connection. Everything works fine on my Windows computer using the Djagno development server Here is my log: 2021-01-01T16:13:18.000000+00:00 app[api]: Build succeeded 2021-01-01T16:13:39.971142+00:00 app[web.1]: [2021-01-01 16:13:39 +0000] [10] [DEBUG] GET / 2021-01-01T16:13:41.373082+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=computer-vision-ml.herokuapp.com request_id=fc6bf181-e15b-4506-8fe5-8714c033406f fwd="83.30.65.205" dyno=web.1 connect=1ms service=1402ms status=503 bytes=0 protocol=https 2021-01-01T16:13:41.376383+00:00 app[web.1]: [2021-01-01 16:13:41 +0000] [21] [INFO] Booting worker with pid: 21 2021-01-01T16:13:41.934138+00:00 app[web.1]: [2021-01-01 16:13:41 +0000] [11] [DEBUG] GET /favicon.ico 2021-01-01T16:13:42.949069+00:00 app[web.1]: [2021-01-01 16:13:42 +0000] [30] [INFO] Booting worker with pid: 30 2021-01-01T16:13:42.943440+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/favicon.ico" host=computer-vision-ml.herokuapp.com request_id=30a20795-6f0b-463c-ba6d-5e72368cd1fc fwd="83.30.65.205" dyno=web.1 connect=1ms service=1010ms status=503 bytes=0 protocol=https Procfile: web gunicorn ComputerVision.wsgi --timeout 15 --keep-alive 5 --log-level debug -
Accessing corresponding object in listview when each object has a form
I am using ListView (and also DetailView) to show the same content for several different objects, and each object is shown with a form. As part of the information, I need to know which object they filled the form out for because the object needs to be a part of the data that I grab from the form. Here's the structure of my code: class ObjectListView(LoginRequiredMixin, FormMixin, ListView): model = Object template_name = 'ui/home.html' context_object_name = 'objects' form_class = OrderForm def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): obj = form.save(commit=False) obj.user = request.user.account obj.save() order_type = form.cleaned_data.get('order_type') price = form.cleaned_data.get('price') messages.success(request, f'Your order has been placed.') return redirect('account') -
How do I find each instance of a model in Django
I am trying to iterate through each instance of a model I have defined. Say I have the following in models.py, under the people django app: class foo(models.Model): name = models.CharField(max_length=20, default="No Name") age = models.PositiveSmallIntegerField(default=0) And I have populated the database to have the following data in foo: name="Charley", age=17 name="Matthew", age=63 name="John", age=34 Now I want to work out the average age of my dataset. In another part of the program (outside the people app, inside the project folder), in a file called bar.py that will be set up to run automatically every day at a specific time, I calculate this average. from people.models import foo def findAverageAge(): total = 0 for instance in //What goes here?// : total += instance.age length = //What goes here, to find the number of instances?// average = total / length return average print(findAverageAge) In the code above, the //What goes here?// signifies I don't know what goes there and need help. Before you downvote for lack of research, I have spent hours scouring the Django documentation and have found nothing on this. Maybe I've been looking in the wrong place, or I guess didn't really know what to search. Still new … -
How do I fix IntegrityError?
I'm learning Django, and I have the following error IntegrityError at /admin/book/book/add/ (1048, "Column 'publication_date' cannot be null") My models are constructed like this from django.db import models class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) website = models.URLField() def __str__(self): return self.name class Meta: ordering = ['name'] class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() def __str__(self): return u'%s %s' % (self.first_name, self.last_name) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete = models.CASCADE) publication_date = models.DateField(null = True ,blank=True) def __str__(self): return self.title What I must do? -
Django: NameError: Slug is not defined
Can anyone advise on how to query the `total_likes of a post to be shown in my HTML, I tried, but was given this error: NameError: Slug is not defined An expert has suggested me to use generic class views which i am not familiar with, is there any other ways i can query the correct post and define the slug? Unsure of why it didnt work for the home feed view but it did work for the detail blog view. Whats wrong actually. I cant include a slug argument in the home view as the url does not contain a . is there really no other way to do it? I think it might be the way I am querying and linking the blog post with the likes but I'm not sure why I'm wrong and I don't know how to modify it despite trying for a few hours. views.py def home_feed_view(request): context = {} blog_posts = sorted(BlogPost.objects.all(), key= attrgetter('date_updated'), reverse = True) blog_post = get_object_or_404(BlogPost, slug=slug) total_likes = blog_post.total_likes() liked = False if blog_post.likes.filter(id=request.user.id).exists(): liked = True context['blog_posts'] = blog_posts context['blog_post'] = blog_post context['total_likes'] = total_likes return render(request, "HomeFeed/snippets/home.html", context) def LikeView(request, slug): context = {} post = … -
Django Allauth set username as Gmail Address
I am new to Django Allauth and am a bit confused and need help I have a custom user model with the following fields username = models.CharField(_('username'), max_length=130, unique=True) full_name = models.CharField(_('full name'), max_length=130, blank=True) is_staff = models.BooleanField(_('is_staff'), default=False) is_active = models.BooleanField(_('is_active'), default=True) date_joined = models.DateField(_("date_joined"), default=date.today) phone_number_verified = models.BooleanField(default=False) change_pw = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True,default=create_new_ref_number()) country_code = models.IntegerField(default='+91') two_factor_auth = models.BooleanField(default=False) I am able to successfully signup a user using gmail signin. However, in the username field, "user" value is saved. I want to save the email address from gmail as username. I have done some research and it seems like I need to write some save signals and add some settings, but I am not really sure what to write where. I have gone through the docs and its a bit confusing. Using SocialAccounts , I am able to get photo and full_name def socialuser(self): data = SocialAccount.objects.get(user=self.id).extra_data nameofuser = data.get('name') return nameofuser def socialuserphoto(self): data = SocialAccount.objects.get(user=self.id).extra_data pictureurl = data.get('picture') return pictureurl I use the href below for both signup or signin a user <a title="Google" class="socialaccount_provider google" style="text-decoration:none;" href="/accounts/google/login/?process=login">Sign in with Google</a> -
Django tamplate can not loaded
I called a template in the django render function, but django cannot find it here is the django view code: from django.shortcuts import render # Create your views here. def home_page(request): return render(request, "index.html") And after this I tried to check my settings.py and urls.py, but found nothing, and the file is also in the tamplate subfolder of the app here is the directory structure: │ .gitignore │ db.sqlite3 │ funcational_test.py │ manage.py │ ├─Terminal_equipment_management │ │ asgi.py │ │ settings.py │ │ urls.py │ │ view.py │ │ wsgi.py │ │ __init__.py │ │ │ └─__pycache__ │ └─webui │ admin.py │ apps.py │ models.py │ tests.py │ views.py │ __init__.py │ ├─migrations │ ├─tamplate index.html the settings.py is: INSTALLED_APPS = [ "api", "webui", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] urls.py is: from django.contrib import admin from django.urls import path, include from webui import views urlpatterns = [ path("", views.home_page, name="home_page"), ] But when I visit localhost:8000/, Django will report TemplateDoesNotExist at / here is some Error Message: Template-loader postmortem Django tried loading these templates, in this … -
Unable to Run Celery and celery beat using docker in django application (Unable to load celery application)
when I am trying to run my application I using without docker its working perfectly , but In docker-compose I am getting this error : | Error: Invalid value for '-A' / '--app': | Unable to load celery application. | The module sampleproject was not found. my docker-compose file app: container_name: myapp hostname: myapp build: context: . dockerfile: Dockerfile image: sampleproject tty: true command: > bash -c " python manage.py migrate && python manage.py runserver 0.0.0.0:8000 " env_file: .env ports: - "8000:8000" volumes: - .:/project depends_on: - database - redis redis: image: redis:alpine celery: build: context: ./ dockerfile: Dockerfile command: celery -A sampleproject worker -l info depends_on: - database - redis celery-beat: build: . command: celery -A sampleproject beat -l info depends_on: - database - redis - celery my Docker file FROM python:3.8 COPY requirements.txt requirements.txt RUN pip install -r requirements.txt --no-cache-dir \ && rm -rf requirements.txt RUN mkdir /project WORKDIR /project my folder structure is something like this : -
how can you return values introduced in a form to the same page? Django
I'm creating an email scrapper that outputs the emails of a specific URL introduced to a form. The problem is that as of now, the email list is printed to another separated URL, but I want it to return to the same page. How could you do this? I'm new Emailsearcher.html: This is the HTML code I have and that I want it to print the form values. As you can see here, I've tried using a loop but it doesn't work. {% include "leadfinderapp/navigation.html" %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> </head> <body> <div class="container"> <br/> <div class="row justify-content-center"> <div class="col-12 col-md-10 col-lg-8"> <form class="card card-sm" action="{% url 'scrap' %}" method="GET"> <div class="card-body row no-gutters align-items-center"> <div class="col-auto"> <i class="fas fa-search h4 text-body"></i> </div> <!--end of col--> <div class="col"> <input type="text" class="form-control form-control-lg form-control-borderless" placeholder="Introduce URL" name="Email" id="InputSearch" value="{{ Email.get }}" aria-describedby="searchHelp"> </div> <!--end of col--> <div class="col-auto"> <button class="btn btn-lg btn-success" type="search">Find Email Address</button> </div> <!--end of col--> </div> </form> </div> <!--end of col--> </div> {% for email in email_list %} <p> {{ email }} </p> {% endfor %} </div> <!-- Begin Page Content --> <!-- /.container-fluid --> <!-- Footer --> {% include 'leadfinderapp/footer.html' %} … -
Is there anyway to send WhatsApp messages to multiple phone numbers in Django using Twilio
I am trying to send the same message to multiple phone numbers using Twilio. This is the code in my views.py file to send WhatsApp message. The for loop is working only for the first number. Is this the right way to call for loops in Django? phone_numbers = ['number-1', 'number-2'] form = MessageForm(request.POST) if request.is_ajax(): if form.is_valid(): body = form.cleaned_data.get('body') for number in phone_numbers: send_whatsapp_message(body, number) return JsonResponse({'body': body}) -
Django REST API with Custom User table
Can someone please provide me a guide/reference using which I can implement user authentication and permission using stored procedure in MySQL? I want to create the user table first. -
django efficient ways to decompose and compose user data to and from bytes
So, I have a concept of a virtual data-store. I want to make sure that Whatever information the user enters, It is converted into binary and stored to the database. Upon retrieval, it must be reconverted from Binary. This is the core idea. Here are my models: class DataSheetField(models.Model): """ Represents a parent which belongs to a dataSheet. Fields have their own data types. Field data is stored in different models, depending on the dataType set. """ class DataTypes(models.TextChoices): """ A list of all the supported dataTypes formatted as different choices. This list is flexible although migrations might take a while. """ FLOAT = 'FLOAT' BOOLEAN = 'BOOLEAN' CHAR = 'CHAR' INTEGER = 'INTEGER' BIG_INTEGER = 'BIG_INTEGER' SMALL_INTEGER = 'SMALL_INTEGER' BYTES = 'BYTES' DATE_TIME = 'DATE_TIME' objects = models.Manager() id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True) name = models.SlugField(max_length=100, validators=[MinLengthValidator(2)], db_index=True) data_type = models.CharField(choices=DataTypes.choices, default=DataTypes.INTEGER, db_index=True, max_length=15) created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True) data = models.ManyToManyField('api_backend.FieldData') ... REQUIRED_FIELDS = [name, data_type] This model DataSheetField can be considered as a field in any normal database. It has it's own data-type which is going to be used to validate the data stored inside it. The field also has a many to many field data. … -
The modified time (auto_now) works on Django but not in Heroku when deployed
So this is my code in class Post(models.Model) class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) and snippet of my code in home.html {% if post.date_modified is not Null %} <small class="text-secondary font-italic">— modified at {{ post.date_modified }}</small> {% endif %} The codes work perfectly in Django, however, when I deployed them in Heroku: the date_modified of posts are filled (same date and time as date_posted) sodate_modified is not Null. This makes them show up even if the post is not updated by the user. I have already done: python manage.py makemigrations python manage.py migrate git add -A, git commit -m "message", git push heroku master heroku run python manage.py makemigrations heroku run python manage.py migrate Does anyone know how to fix this or explain why this happened? I can't seem to find any solution related to this. Maybe I missed something. -
Django User model saves twice into database
I am trying to create multi user registration system with Django. However, anytime I call the save() method to save a User type, it saves into the User table twice. The funny thing about the second model that is saved is that many required fields are empty. I am using a custom user model that I created from AbstractBaseUser. I also rewrote the forms for the CustomUser model. For the multiple user types, I am using a profile model (Student model has a OneToOne field to the user model) models.py: class User(AbstractBaseUser, PermissionsMixin): # I've removed some unimportant code here email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) class Types(models.TextChoices): STUDENT = 'STUDENT', 'Student' DEPARTMENT_USER = 'DEPARTMENT_USER', 'Department user' ADMIN = 'ADMIN', 'Admin' user_type = models.CharField(_('Type'), max_length=50, choices=Types.choices, default=Types.STUDENT) first_name = models.CharField(_('First name'), max_length=70, blank=False, default="") middle_name = models.CharField(_('Middle name'), max_length=70, blank=True, default="") last_name = models.CharField(_('Last name'), max_length=70, blank=False, default="") is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) # a admin user; non super-user is_superuser = models.BooleanField(default=False) # a superuser last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['user_type', 'first_name', 'last_name'] # Email & Password are required by default. objects = UserManager() class Meta: verbose_name … -
I want to add Foreign Key to Model Messages of model Namefor link, but i am getting this error. i am new to django so i dont understand the error
models.py from django.db import models import uuid # Create your models here. class NameforLink(models.Model): name=models.CharField( max_length=50) id=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) def __str__(self): return self.name class Messages(models.Model): id=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name_id=models.ForeignKey(NameforLink, on_delete=models.CASCADE, default=uuid.uuid4, related_name='name_id') checkbox1=models.CharField(max_length=50, default='') checkbox2=models.CharField(max_length=50, default='') commentbox=models.CharField(max_length=500, default='', null=True, blank=True) THIS is the error message: in check_constraints raise IntegrityError( django.db.utils.IntegrityError: The row in table 'comment_messages' with primary key '1' has an invalid foreign key: comment_messages.nameId_id contains a value '4f25c6ae984345d081e2c1373bed61d9' that does not have a corresponding value in comment_nameforlink.id. -
How to execute jQuery code before submitting the form
How do I make my jQuery code execute before submit and before sending it to database? I'm trying to take user input from checkbox, process it in jQuery and send this value to a hidden html field. When executing separately the code works as it should, console.log returns correct value, however when executed inside the project Django returns error that the value is empty ("") and jQuery alert added for debugging does not execute. <form id="cat-form" action="" method="post"> {% csrf_token %} <ul> <p>Imię:</p> <input type="text" id="name" name="cat_name" required> </ul> <ul> <p>Question?</p> <input type="radio" id="f_low" name="friendliness" value="0" required> <label for="f_low">Answer 1</label> <br> <input type="radio" id="f_medium" name="friendliness" value="1"> <label for="f_medium">Answer 2</label> <br> <input type="radio" id="f_high" name="friendliness" value="2"> <label for="f_high">Answer 3</label> </ul> <ul><input type="hidden" id="friendliness_level" name="friendliness_level"></ul> <input type="submit"/> </form> Script: <script type = "text/javascript" language = "javascript"> $('#cat-form').submit(function() { // Take html user input into variables var friendliness = $("input[type=radio][name=friendliness]:checked").val(); // populate hidden fields with variable values $('#friendliness_level').val(friendliness); console.log($('#friendliness_level').val()) }); </script> views.py def cat_create(request): if request.method == 'POST': cat = Cat() cat.friendliness_level = request.POST.get('friendliness_level') cat.save() return render(request, 'cats/cat_description.html') else: return render(request, 'cats/cat_description.html') -
Value: abc must be an instance of <class 'dict'> with EmbeddedField
Trying use EmbeddedField of Djongo but without any success. Output error: Value: abc must be an instance of <class 'dict'> class MetaData(models.Model): title = models.CharField(max_length=255) keyword = models.CharField(max_length=255) def __str__(self): return self.title class Meta: abstract = True class Posts(models.Model): _id = models.ObjectIdField() heading = models.CharField(max_length=255) content = models.TextField() metadata = models.EmbeddedField(model_container=MetaData) objects = models.DjongoManager() def __str__(self): return self.heading Preview error on Django Admin: python: 3.8.0 MondoDB: 4.4.3 Django: 3.0.5 Djongo: 1.3.3 -
how can i order by data per group by in django ORM
I have 3 models in django ORM like this class Singer(m.Model): name = m.CharField(max_length=50) class Music(m.Models): singer = m.ForeignField("singer") title = m.CharField(max_length=50) class PlayedHistory(m.Models): played_time = m.DateTimeField(auto_now_add=True) music = m.ForeignField("music") and I want to get top 3 singer of music played per month using PlayedHistory like... Date | Singer | PlayCount | LastPlayed | ---------------------------------------------- 202012 singer1 40000 202101T12:30:12 (202012 top1) 202012 singer2 39000 202101T11:10:22 (202012 top2) 202012 singer3 38000 202101T10:10:22 (202012 top3) 202011 singer2 90000 202011T11:11:55 (202011 top1) 202011 singer5 87000 202011T11:11:14 (202011 top2) 202011 singer4 50000 202012T08:13:52 (202011 top3) ... 201912 singer4 10000 202012T08:13:52 i tried to using orm queryset, first group by singer and count played PlayedHistory.objects.\ values('music__singer__name').\ annotate(Singer=F('music__singer__name'), PlayCount=Count('id')).\ values('Singer', 'PlayCount').order_by('PlayCount') So the result is ... | Singer | PlayCount | -------------------------- singer2 129000 singer5 87000 singer4 50000 singer1 40000 singer3 39000 but i wonder how can i group per one month and show just top 3 record... please some information or advice thank you :) -
How to implement JavaScript in Django?
I am creating a basic To-Do web app and I'm struggling with the last part - which is implementing JavaScript in Django. I created a separate .js file in a static folder. // Create a "close" button and append it to each list item var myNodelist = document.getElementsByTagName("LI"); var i; for (i = 0; i < myNodelist.length; i++) { var span = document.createElement("SPAN"); var txt = document.createTextNode("\u00D7"); span.className = "close"; span.appendChild(txt); myNodelist[i].appendChild(span); } // Click on a close button to hide the current list item var close = document.getElementsByClassName("close"); var i; for (i = 0; i < close.length; i++) { close[i].onclick = function() { var div = this.parentElement; div.style.display = "none"; } } // Add a "checked" symbol when clicking on a list item var list = document.querySelector('ul'); list.addEventListener('click', function(ev) { if (ev.target.tagName === 'LI') { ev.target.classList.toggle('checked'); } }, false); // Create a new list item when clicking on the "Add" button function newElement() { var li = document.createElement("li"); var inputValue = document.getElementById("myInput").value; var t = document.createTextNode(inputValue); li.appendChild(t); if (inputValue === '') { alert("You must write something!"); } else { document.getElementById("myUL").appendChild(li); } document.getElementById("myInput").value = ""; var span = document.createElement("SPAN"); var txt = document.createTextNode("\u00D7"); span.className = "close"; span.appendChild(txt); li.appendChild(span); for (i … -
Djoser authentication working differently on production server than development
I have been working on getting logins working with both emails and usernames, and I ended up finding this link. The first answer on that worked excellently in my development environment, and I was very happy with how simple the solution was, but doesn't work at all on my production server. Here is what I have tried: Checking python versions are the same Checking django versions are the same Checking djoser versions are the same Checking simplejwt versions are the same Removed and replaced all code on production server using git Removed and replaced all code on production server using ftp Checked that the code in the models.py file is correct Replaced the database with the local database Deleted and rebuilt the virtual environment Checked for errors in the logs Opened port 8000 on the production server and served it with manage.py runserver No matter what I do, I still get {"detail": "No active account found with the given credentials"} as the response when using email as the username, but things work fine when using the username as the username. I have no idea where to check now. As far as I can tell, there is absolutely no difference between … -
how to make some part of the page as unauthenticated in django?
I have a Django project which uses JWT as the authentication class. But for certain pages of my app has no authentication. But still when I make request it returns the following thing. { "detail": "You do not have permission to perform this action." } My authentication classes are here REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } My views file is here class Hello(APIView): authentication_classes = [] def post(self, request): return Response('Hello') So how do I achieve this thing?