Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running aggregate function on Django queryset union with renamed fields raises django.db.utils.DatabaseError
I am using Django 3.2 I am trying to create a query that queries two different models and does the following: renames the returned columns (so the queries can be 'union'ed together 'unions' the two querysets (after column rename using annotate) tries to run an aggregate function Sum on the union (this is where it barfs). This is a simplified version of my codebase: Models class EventCategory(models.Model): name = models.CharField(max_length=16) class Event(models.Model): name = models.CharField(max_length=32) category = models.ForeignKey(EventCategory, on_delete=models.CASCADE) class Tournament(models.Model): name = models.CharField(max_length=32) category = models.ForeignKey(EventCategory, on_delete=models.CASCADE) prize_money = models.IntegerField() class TournamentAward(models.Model): awardee = models.ForeignKey(setting.AUTH_USER_MODEL, on_delete=models.CASCADE) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Game(models.Model): player = models.ForeignKey(setting.AUTH_USER_MODEL, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) payment = models.SmallPositiveInteger() created_at = models.DateTimeField(auto_now_add=True) Queries payment_earned_today = Game.objects.filter( player=user, created_at__year=year, created_at__month=month, created_at__day=day ).annotate(category=models.F('event__category'))\ .only('category','payment') tournament_prize_today = TournamentAward.objects.filter( awardee=user, created_at__year=year, created_at__month=month, created_at__day=day ).select_related('tournament__category')\ .annotate(category=models.F('tournament__category'))\ .annotate(payment=models.F('tournament__prize_money'))\ .only('category','payment') # Union the two querysets ... union_queryset = payment_earned_today.union( tournament_prize_today ) results = union_queryset.aggregate(total=models.Sum('payment')) On the line when I try to calculate the total, I get the following error: django.db.utils.DatabaseError: ORDER BY not allowed in subqueries of compound statements How can I union two models and calculate an aggregate function on the union? -
Django Signals Python
In this piece of code i want to get text from reacently created data in model models.py: from django.db import models class Tokenize(models.Model): text = models.TextField() class Pos(models.Model): POS_TAGS = [ ('NOUN', 'NOUN'), ('ADJ', 'ADJ'), ('NUM', 'NUM'), ('PRON', 'PRON'), ('ADV', 'ADV'), ('VERB', 'VERB'), ('CNJ', 'CNJ'), ('ADP', 'ADP'), ('PRT', 'PRT'), ('INTJ', 'INTJ'), ('MOD', 'MOD'), ('IMIT', 'IMIT'), ('AUX', 'AUX'), ('PPN', 'PPN'), ('PUNC', 'PUNC'), ('SYM', 'SYM') ] token = models.CharField(max_length=150) pos = models.CharField(max_length=150, choices=POS_TAGS, null=True, default='NOUN') signals.py: from django.db.models.signals import post_save from django.dispatch import receiver from .models import Tokenize, Pos from uztagger import Tagger Uztagger tags each word in text example: input: "White board" output: [('White', 'ADJ'), ('board', 'NOUN')] but it's for Uzbek language @receiver(post_save, sender=Tokenize) def create_profile(sender, instance, created, **kwargs): tagger = Tagger() if created: text = instance.text # there i should get text of receantly created data tokens = tagger.pos_tag(text) for token in tokens: a = Pos(token=token[0], pos=token[1]) # and there i should create tagged data a.save() I should get data from instace and post in other model -
How to pass a variable into a django admin page?
I have an app in my django project, and I need to display a list in one of its model's templates. How to pass the variable of this list to this model's template? ! I know that there are some almost simular questions but I didn't really understand the answers so they didn't help me. If you have read to this line, thank you a lot for your attention. -
Django file based email backend
It's probably something very obvious, but I can't seem to figure it out. This snippet is from Django's file based email backend (django.core.mail.backends.filebased.py) def write_message(self, message): self.stream.write(message.message().as_bytes() + b"\n") My question is. How can I find out what class is message an object of? Context for why: My code sends emails along various execution paths. I want to leverage Django's filebased backend, instead of firing live emails during debugging and unit testing (or creating my own file based system). The relevant code has a MIMEMultipart object currently (with utf-8 coded text) that works fine for production. I need to be able to convert that into an object that can be printed legibly by the above snippet. PS: I come from a C++ background where this would've been an easy question to answer. -
Getting error 'context must be a dict rather than set.' when trying to retrieve single object where id=id in django Model
I can't make work my detail function to simply retrieve all fields of only one Model element. my code is : views.py def band_detail(request, id): band = Band.objects.get(id=id) return render(request, 'bands/band_detail.html', {'band', band }) in urls.py I wrote: path('bands/<int:id>/', views.band_detail) So, when I am going to /bands/{id} it should show me my band_details.html page : {% extends 'listings/base.html' %} {% block content %} <h1> {{ band.name }} </h1> {% if band.active %} <h2> Active : <i class="fa-solid fa-check"></i> </h2> {% else %} <h2> Active : <i class="fa-solid fa-xmark"></i> </h2> {% endif %} {% endblock %} but instead I get a typeError telling me : 'context must be a dict rather than set.' error page I guess this is due to the way I retrieve my Band object from id. But I can't wrap my mind around. That is why I am coming for a lil help. Thanks in advance -
django loading seeds not working - loaddata
I have created the following seed to load into my database [ { "model": "authentication.role", "fields": { "description":"admin", "state": 1, "created_at": "2020-01-01T00:00:00Z", "updated_at": null } }, { "model": "authentication.role", "fields": { "description":"leader", "state": 1, "created_at": "2020-01-01T00:00:00Z", "updated_at": null } }, { "model": "authentication.role", "fields": { "description":"user", "state": 1, "created_at": "2020-01-01T00:00:00Z", "updated_at": null } } ] when I run the command to load the seeds python3 manage.py loaddata core/seeds/role.json I receive the message that they have been inserted correctly. but only the last record of the object appears in my database why if django tells me that 3 records were inserted only one appears? this is my model class Role(models.Model): id = models.CharField(default=str(uuid.uuid4()), max_length=255, unique=True, primary_key=True, editable=False) description = models.TextField(blank=True) state = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True, default=None) -
Django/Wagtail Snippet Serializer in API
I have added wagtail CMS's blog author in my 'models.py' also exposed it in API, but it's showing like this in API "blog_authors": [ { "id": 1, "meta": { "type": "blog.BlogAuthorsOrderable" } } ], Here's the models.py code class BlogAuthorsOrderable(Orderable): """This allows us to select one or more blog authors from Snippets.""" page = ParentalKey("blog.AddStory", related_name="blog_authors") author = models.ForeignKey( "blog.BlogAuthor", on_delete=models.CASCADE, ) panels = [ # Use a SnippetChooserPanel because blog.BlogAuthor is registered as a snippet SnippetChooserPanel("author"), ] @register_snippet class BlogAuthor(models.Model): """Blog author for snippets.""" name = models.CharField(max_length=100) website = models.URLField(blank=True, null=True) image = models.ForeignKey( "wagtailimages.Image", on_delete=models.SET_NULL, null=True, blank=False, related_name="+", ) panels = [ MultiFieldPanel( [ FieldPanel("name"), # Use an ImageChooserPanel because wagtailimages.Image (image property) # is a ForeignKey to an Image ImageChooserPanel("image"), ], heading="Name and Image", ), MultiFieldPanel( [ FieldPanel("website"), ], heading="Links" ) ] def _str_(self): """String repr of this class.""" return self.name class Meta: # noqa verbose_name = "Blog Author" verbose_name_plural = "Blog Authors" How do I serialize like this show author name, website, image and id? I tried to Serialize the BlogAuthor class AuthorSerializer(serializers.ModelSerializer): class Meta: model = BlogAuthor fields = ( "id", "name", "website", "image", ) And here is the API field APIField("blog_authors", serializer=AuthorSerializer(many=True)), When I … -
pass a variable between multiple custom permission classes in drf
I have a base permission class that two ViewSets are sharing and one other permission class each that is custom to each of the ViewSets, so 3 permissions all together, is there a way to pass a specific variable down from the base permission class to the other permission classes? My setup looks like this: class BasePerm(permissions.BasePermission): def has_permission(self, request, view): some_var = # call an API using request variable class Perm1(permissions.BasePermission): def has_permission(self, request, view): # get the value of some_var from BasePerm class Perm2(permissions.BasePermission): def has_permission(self, request, view): # get the value of some_var from BasePerm class MyViewSet1(mixins.CreateModelMixin, viewsets.GenericViewSet): permission_classes = [BasePerm, Perm1] class MyViewSet2(mixins.CreateModelMixin, viewsets.GenericViewSet): permission_classes = [BasePerm, Perm2] -
How can I get cleaned_data from html form?
I have django app with class based view and form written in html: <form method="post" action="{% url 'personal-account' %}"> {% csrf_token %} <div class="page slide-page"> <div class="field"> <input type="text" placeholder="First name" class="input_1" name="first_name" size="1" value="{{ data.first_name }}"> <input type="text" placeholder="Last Name" class="input_2" name="last_name" size="1" value="{{ data.last_name }}"> </div> <div class="middle"> <input type="text" placeholder="Username" class="input_3" name="username" size="1" value="{{ data.username }}"> <input type="text" placeholder="Email" class="input_6" name="email" size="1" value="{{ data.email }}"> </div> <div class="last"> <input type="password" placeholder="Password" class="input_4" name="password" size="1" value="{{ data.password }}"> <input type="password" placeholder="Confirm" class="input_5" name="confirm_password" size="1" value="{{ data.confirm_password }}"> </div> <div class="field"> <button type="submit" class="submit-btn">Submit</button> </div> </div> </form> View class PersonalSignup(View): def post(self, request): return render(request, 'authentication/personal_signup.html') def get(self, request): return render(request, 'authentication/personal_signup.html') Now I want to get all values from inputs(first_name, last_name...) with cleaned_data. -
As a Benevole, how i can create a view for participate in a given mission [closed]
models.py class ProfileBenevole(models.Model): ville = [ ('--Aucun--', '--Aucun--'), ('Agadir', 'Agadir'), ('Casablanca', 'Casablanca'), ('Essaouira', 'Essaouira'), ('Fes', 'Fes'), ('Marrakech', 'Marrakech'), ('Meknes', 'Meknes'), ('Oujda', 'Oujda'), ('Rabat', 'Rabat'), ('Tanger', 'Tanger'), ('Tetouan', 'Tetouan'), ] activiter_prefere = ( ('Cadre', 'Cadre'), ('Salarié', 'Salarié'), ('Sans emploi', 'Sans emploi'), ('Commercent', 'Commercent'), ('Etudiant', 'Etudiant'), ('Autre', 'Autre'), ) user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) photo_profile = models.ImageField( upload_to='uploads/images',null=True,blank=True) nomComplet = models.CharField(max_length=50,null=True) telephone = models.CharField(max_length=20,null=True) adresse = models.CharField(max_length=100,null=True) date_naissance = models.DateTimeField(auto_now_add=True, null=True) cin = models.CharField(max_length=12, null=True) domaine_experience = models.TextField(null=True) biographie = models.TextField(null=True, blank=False) activiter_prefere = models.CharField(max_length=100, choices=activiter_prefere) ville =models.CharField(max_length=100,choices=ville) def __str__(self): return self.user.username class Mission(models.Model): domaine_prefere = ( ('Sport', 'Sport'), ('Santer', 'Santer'), ('Soutien Scolaire', 'Soutien Scolaire'), ('Aides Sociales', 'Aides Sociales'), ('Entreprenariat', 'Entreprenariat'), ('Informatique', 'Informatique'), ('Animation', 'Animation'), ) nom=models.CharField(max_length=50,null=False,blank=False) description=models.CharField(max_length=150,null=False,blank=False) date_publier=models.DateTimeField() date_modification=models.DateTimeField(auto_now=True) domaine=models.CharField(max_length=20, choices=domaine_prefere) lieu=models.CharField(max_length=50,null=False,blank=False) nombre_participant=models.CharField(max_length=50,null=False,blank=False) photo_mission = models.ImageField( upload_to='uploads/images',null=True,blank=True) slug=models.SlugField(null=True,blank=True) participe=models.ManyToManyField(ProfileBenevole,related_name='participer') class Meta: ordering = ('-date_publier',) def save(self,*args, **kwargs): if not self.slug: self.slug=slugify(self.nom) super(Mission,self).save(*args, **kwargs) def __str__(self): return self.nom -
how to access foreign table field in django view
I have two models, the plans model & plans features ( foreign relation with plans table), given below: Following is the view which returns an object of features for each plan: Now I want to access, the "price" field of the plans table (model). How this is possible? my Django template is the following which doesn't work: I belive there is solution to this, I would love hear from you . thank you -
how to run function encryption in django
so i have function for encryption in views.py. the file is saved at models. i want to run the function to know if the function is work. but i don't know how to run the function or code in urls.py here's my views.py : key_bytes = 16 testaudio = Audio_store.objects.all().values_list('audio').last() key = 'testing' # Takes as input a 32-byte key and an arbitrary-length plaintext and returns a # pair (iv, ciphtertext). "iv" stands for initialization vector. def encrypt(key, testaudio): assert len(key) == key_bytes print(testaudio) print(key) # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) # Create AES-CTR cipher. aes = AES.new(key, AES.MODE_CTR, counter=ctr) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(testaudio) print(iv) print(ciphertext) return (iv, ciphertext) testaudio got by user add it from html. -
Django Numpy ImportError with Apache but not on runserver
so i've tried every other thread and their suggested solutions but without success so far. I have a Django app with a virtualenv and Apache 2.4 and mod_wsgi, which i developed on other server. Now, I'm migrating (rebuilding from scratch) everything on another server. While everything else works, when i tried to install pandas, the app served through Apache throws me an ImportError for Numpy. Original error was: /optilab/env/lib64/python3.6/site-packages/numpy/core/_multiarray_umath.cpython-36m-x86_64-linux-gnu.so: failed to map segment from shared object Thing is, this doesn't happen while using runserver with manage.py . Everything is the same: Python Version (3.6.8), Python Executable (/optilab/env/bin/python) except the Python Path order. For the testing runserver, this is the Python Path list: ['/optilab', '/optilab/env/lib64/python3.6/site-packages', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/optilab/env/lib64/python3.6/site-packages', '/optilab/env/lib/python3.6/site-packages', '/home/appuser/.local/lib/python3.6/site-packages', '/usr/local/lib64/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages', '/env/lib64/python3.6/site-packages'] But, for the app served through Apache, the Python Path is: ['/optilab', '/optilab/core', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/optilab/env/lib64/python3.6/site-packages', '/optilab/env/lib/python3.6/site-packages', '/usr/local/lib64/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages'] I suspect that the list order is the culprit for this problem, but it seems i'm not able to change it. My file structure is the following: /optilab /core <-- startproject directory /env <-- virtualenv files /static /media ... other apps This is the first part of my apache config (BTW, I tried … -
Docker domain name not redirecting to HTTP or HTTPS
I have deployed a Django project using Docker and Nginx. All the process has gone well, but I am having a little issue. I am using certbot for HTTPS, and the redirection from HTTP to HTTPS works fine, but the problem is when I just type the domain name, without HTTP or HTTPS. If I type just the domain name in the URL (example.com) page doesn't load. And if y type http://example.com or https://example.com, everything works perfect. What could be the problem? How can I do to redirect the domain name to HTTPS? My Nginx configuration is the next one: server { listen 80; server_name ${DOMAIN}; location /.well-known/acme-challenge/ { root /vol/www/; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; server_name ${DOMAIN}; ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem; include /etc/nginx/options-ssl-nginx.conf; ssl_dhparam /vol/proxy/ssl-dhparams.pem; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } -
Error while installing psycopg2 using pip
I am trying to run docker in django using this command docker build -t myimage . Now the docker file tries to run the RUN pip install -r /app/requirements.txt --no-cache-dir but when ot gets to the Downloading psycopg2-2.9.3.tar.gz (380 kB) section, it throws the error. NOTE: i do not have psycopg2 in my requirements.txt file only the psycopg2-binary. requirements.txt file ... dj-database-url==0.5.0 Django==3.2.7 django-filter==21.1 django-formset-js-improved==0.5.0.2 django-heroku==0.3.1 psycopg2-binary python-decouple==3.5 ... Downloading pytz-2022.2.1-py2.py3-none-any.whl (500 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 500.6/500.6 kB 2.6 MB/s eta 0:00:00 Collecting psycopg2 Downloading psycopg2-2.9.3.tar.gz (380 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 380.6/380.6 kB 2.7 MB/s eta 0:00:00 Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'error' error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [23 lines of output] running egg_info creating /tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info writing /tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-383i9hb2/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI … -
Django : Transfer data to another view by a button
I have a table of clients where each line has a button to redirect to another page with the id of the client. I do not want that it is on the URL, so I want to avoid a GET method, it is why I thought to us a POST method with the buttons. I did something but it is not working, I have an error message "Method Not Allowed (POST)" with the specific URL. html <table id="customers" class="table table-sortable"> <tr> <th>Référence Client</th> <th>Client</th> <th>Edit</th> </tr> {% for client in query_list_client %} <tr> <td>{{ client.id }}</td> <td>{{ client }}</td> <td> <a href="{% url 'modifyclient' uuid_contrat uuid_group % }" class="btn btn-primary" >Modify</a> <form action="{% url 'selectsaletype' uuid_contrat uuid_group %}" method="POST"> {% csrf_token %} <button name = 'client' type ='submit' value="{{ client.id }}" class='btn btn-secondary' > Select </button> </form> <!-- <a href="{% url 'selectsaletype' uuid_contrat uuid_group client.id % }" class="btn btn-secondary" >Selectionner</a> --> </td> </tr> {% endfor %} </table> urls urlpatterns = [ path('<str:uuid_contrat>/<str:uuid_group>/sales/selectclient/', ListSelectClient.as_view(), name="selectclient"), path('<str:uuid_contrat>/<str:uuid_group>/sales/selectsaletype/', SelectSaletType.as_view(), name="selectsaletype"), ] views class SelectSaletType(ListView): model = ListSaleType paginate_by =10 template_name = 'sales/selectsaletype.html' context_object_name = 'query_sale_type' def get_context_data(self, *args, **kwargs) : context = super(SelectSaletType, self).get_context_data(*args, **kwargs) context['uuid_contrat'] = self.kwargs['uuid_contrat'] context['uuid_group'] = self.kwargs['uuid_group'] print(self.request.POST) return … -
Test form_valid() in Createview
I am trying to test one of my CreateViews. The whole view looks like this: class BookCreate(CreateView): model = Book form_class = BookForm template_name = 'base/components/form.html' def form_valid(self, form): form.instance.user = self.request.user form.save() return HttpResponse( status=204, headers={ 'HX-Trigger': json.dumps({ "bookListChanged": None, }) }) The part of the view that needs testing according to coverage.py is this part: form.instance.user = self.request.user form.save() return HttpResponse( My test right now looks like this: class TestBookViews(TestCase): def setUp(self) -> None: self.user = User.objects.create_user(email='test@gmail.com', password='teSTpassword123') self.client.login(email='test@gmail.com', password='teSTpassword123') return super().setUp() def test_book_create(self): response = self.client.post(reverse('base:book-create'), { 'name': 'TestBook', 'user': self.user, 'publishing_date': '2022-08-17', }) self.assertEqual(response.status_code, 204) But this test does not make it covered. What I am missing? -
How to show all the lesson urls present in a lesson list?
I would like to retrieve lesson urls present in lesson model. class Course(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() price = models.FloatField() class Lesson(models.Model): title = models.CharField( max_length=200) course = models.ForeignKey(Course, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) class LessonURL(models.Model): category = models.ForeignKey(Lesson, on_delete=models.CASCADE) title = models.CharField(max_length=200) video_url = models.URLField() Below is my views.py def courseDetail(request, category_slug, course_slug): try: course_detail = Course.objects.get(category__slug=category_slug, slug=course_slug) all_lessons = Lesson.objects.filter(course=course_detail).order_by('created_date') all_lesson_urls = LessonURL.objects.filter(category__id=all_lessons) except Exception as e: raise e context = { 'course_detail': course_detail, 'all_lessons': all_lessons, 'all_lesson_urls': all_lesson_urls, } return render(request, 'course-detail.html', context) Here is my urls.py urlpatterns = [ path('<slug:category_slug>/<slug:course_slug>/', views.courseDetail, name='course-detail'), ] I am trying to explain my issue with the bellow example Ex: Course: "How to Learn Django" In that course i have 3 Lessons i.e Lesson 1, Lesson 2, Lesson 3 And each lesson contains multiple lesson urls. i.e Lesson 1: URL1, URL2, URL3 - Lesson 2 Contains URL4, URL5, URL6, and so on.. So i am facing the issue while extracting the lesson Urls. Now when i run the above code then its showing. Lesson 1 - (URL1, URL2, URL3, URL4, URL5, URL6) Lesson 2 - (URL1, URL2, URL3, URL4, URL5, URL6) But i wanted to show like … -
How do I filter a django model into ChartJS
Im new to Django and Im working on this project where I need to plot the number of employees based on a given hour. Model class Employe(models.Model): name = models.CharField(max_length=20) monday = models.CharField(max_length=20) tuesday = models.CharField(max_length=20) wednesday = models.CharField(max_length=20) thursday = models.CharField(max_length=20) friday = models.CharField(max_length=20) saturday = models.CharField(max_length=20) sunday = models.CharField(max_length=20) def __str__(self): return self.name Every row contains the name of the employee as well as the hour their shift starts at for each day of the week. I want the user to be able to select a certain day (for instance Monday) so that the graph shows how many employees work throughout the day (00:00 -> 23:59) Chart <canvas id="myChart" width="400" height="350"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for emp in employe %} '{{emp.monday}}', {% endfor %}], datasets: [{ label: '# Des employes', data: [], fill: true,}] options: { scales: { y: { beginAtZero: true } } } }); </script> -
What is the best way to transition from imp to importlib for CloudLinux Passenger WSGI files?
I am looking for the best way to transition from imp to importlib with my passenger_wsgi.py file using importlib as recommended by pylint. My passenger file looks like this: import imp import os import sys sys.path.insert(0, os.path.dirname(__file__)) wsgi = imp.load_source('wsgi', 'core/wsgi.py') application = wsgi.application I have seen some examples using importlib.utils.find_spec(path) and some using importlib.machinery.SourceFileLoader('name','script') Does anyone have an example for their passenger_wsgi.py file that uses the newer method with importlib that would be the new standard they could share? -
import cv2 error on django ImportError: libGL.so.1
i'm working on a django project and i need to use the webcam. i've tried to install opencv-python with pip but python give me back the error ImportError: libGL.so.1: cannot open shared object file: No such file or directory. i've tried to install libGL.so.1 inside Dockerfile: RUN apt-get update RUN apt-get install libgl1 -y but I haven't solved my problem. -
httpd (apache) server django website hosting
I want to host my website on a VPS with Centos 7 I setup httpd (apache) server and set all the configuration in "/etc/httpd/conf/httpd.conf" file but it doesn't work. when i try to access my website in the browser, it will take a lot of time and finally it returns an error 500 & says that there is a problem in your configuration file. can you please check my file, whats wrong with this. # # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot … -
Performing group by and aggregrate Django
How can I do the following in Django? SELECT AVG(calories) AS AVG_DAILY_CALORIES FROM ( SELECT date, SUM(calories) FROM products_eaten GROUP BY date ) daily_calories I already have the subquery itself with values and annotate. Adding aggregate after this fails. Thanks in advance! -
DoesNotExist at /settings Profile matching query does not exist. django error
this is the profile model class Profile(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) id_user=models.IntegerField() bio=models.TextField(blank=True) profileimg=models.ImageField(upload_to='profile_images',default='defualtdp.png') location=models.CharField(max_length=100,blank=True) def _str_(self): return self.user.username and in the views.py i tried to get the object like this def settings(request): user_profile=Profile.objects.get(user=request.user) return render(request,'setting.html',{'user_profile':user_profile}) and passed into settings.html <img src="{{user_profile.profileimg.url}}"> <textarea id="about" name="bio" rows="3" class="shadow-none bg-gray-100">{{user_profile.bio}}</textarea> <input type="text" name="location" value="{{user_profile.location}}" class="shadow-none bg-gray-100"> and its showing the error DoesNotExist at /settings Profile matching query does not exist. I am really dont know what to do... -
Use m2m_changed signal on model with related manager
I can set up a m2m_changed signal on one side of the relationship but not both. for example: This works: class Topping(models.Model): # ... pass class Pizza(models.Model): # ... toppings = models.ManyToManyField(Topping) from django.db.models.signals import m2m_changed def toppings_changed(sender, **kwargs): # Do something pass m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through) But the following gives me the error AttributeError: type object 'Topping' has no attribute 'pizza_set' even though Topping.pizza_set.all() or Topping.pizza_set.through is successful in the shell: class Topping(models.Model): # ... pass class Pizza(models.Model): # ... toppings = models.ManyToManyField(Topping) from django.db.models.signals import m2m_changed def toppings_changed(sender, **kwargs): # Do something pass m2m_changed.connect(toppings_changed, sender=Topping.pizza_set.through)