Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Paginate tabs element with Bootstrap - Jquery
I would like to paginate bootstrap tabs buttons. Let's say, after 50 buttons, I would like to display them paginated, so the list doesn't get too long. So far, I wasn't able to find help anywhere so I tried to figure it out by myself but I couldn't reach my goal. WHAT I WANT TO ACHIEVE I post a picture for better understanding: WHAT I ACHIEVED SO FAR let listElement = $(".paginator"); let perPage = 50; let numItems = document.getElementById("numOfQuestions").value; let numPages = Math.ceil(numItems / perPage); $(".pager").data("curr", 0); let curr = 0; while (numPages > curr) { $('<li><a href="#" class="page_link">' + (curr + 1) + "</a></li>").appendTo( ".pager" ); curr++; } $(".pager .page_link:first").addClass("active"); listElement.children().css("display", "none"); listElement.children().slice(0, perPage).css("display", "block"); $(".pager li a").click(function () { let clickedPage = $(this).html().valueOf() - 1; goTo(clickedPage, perPage); }); function previous() { let goToPage = parseInt($(".pager").data("curr")) - 1; if ($(".active").prev(".page_link").length == true) { goTo(goToPage); } } function next() { goToPage = parseInt($(".pager").data("curr")) + 1; if ($(".active_page").next(".page_link").length == true) { goTo(goToPage); } } function goTo(page) { let startAt = page * perPage, endOn = startAt + perPage; listElement .children() .css("display", "none") .slice(startAt, endOn) .css("display", "block"); $(".pager").attr("curr", page); } <div class="col-md-3"> <div class="nav nav-pills" id="v-pills-tab" role="tablist" aria-orientation="vertical"> <input type="hidden" name="" … -
How mock stripe in Django unit test
We used stripe for the payment system and stripe testing docs is its test doc. I want to mock Stripe in order to test our payment system but the stripe invoice total cost is zero all the time. I mocked stripe.InvoiceItem.create and stripe.Invoice.finalize_invoice and stripe.Invoice.create like this: @patch("app_name.models.stripe.InvoiceItem.create") @patch("trips.models.stripe.Invoice.finalize_invoice") @patch("trips.models.stripe.Invoice.create") def test_method( self, mock_create, mock_finalize, mock_invoice_item, ): response = MagicMock() # api_key and stripe_account from this link https://stripe.com/docs/api/connected_accounts response.api_key = "sk_test_MSc53AbTknQXPy" response.stripe_account = "acct_1032D82eZvKYlo2C" # Stripe account ID response.stripe_version = "2022-08-01" # last version here https://stripe.com/docs/upgrades mock_invoice_item.return_value = response response = MagicMock() geofencing_zone = GeofencingZone.objects.get(properties__name="Zone A") response.total = geofencing_zone.properties.delivery_price.price response.invoice_pdf = "https://google.com" response.id = "sk_test_MSc53AbTknQXPy" mock_create.return_value = response mock_finalize.return_value = response.id now I think maybe I should use stripe-mock somehow to mock stripe, but I can not understand how? -
Why my form not sowing any validation errors after i click the submit button in django?
I've two forms rendering in a single function based view, it is diplaying validation errors of only one form when i click the signup button but when i click the login button it just reload my page and doesn't showing any validation error views.py def register(request): form = RegisterForm() form_b = LogInForm() if request.POST.get('submit') == 'sign_up': form = RegisterForm(request.POST) if form.is_valid(): form.save() elif request.POST.get('submit') == 'log_in': form1 = LogInForm(request=request, data=request.POST) if form1.is_valid(): uname = form1.cleaned_data['username'] upass = form1.cleaned_data['password'] user = authenticate(username=uname, password=upass) if user is not None: login(request, user) return redirect('/shop/') else: form = RegisterForm() form_b = LogInForm() return render(request, 'reg.html', {'form': form, 'form1': form_b}) forms.py from distutils.command.clean import clean from xml.dom import ValidationErr from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): password1 = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['username', 'email'] class LogInForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput()) password = forms.CharField(widget=forms.PasswordInput()) reg.html <form class="loginForm" action="" method="POST" novalidate> {% csrf_token %} {% for field in form %} <p> {{field.label_tag}} {{field}} </p> <p> {{field.errors}} </p> {% endfor %} <button type="submit" class="btnLogin" name='submit' value='sign_up'>Sign Up</button> </form> <form class="loginForm" action="" method="post" novalidate> {% csrf_token %} {% for field in form1 %} <p> {{field.label_tag}} {{field}} </p> <p> … -
Django Paginator returns results of the last page despite page number being greater than the last feasible page
Lets say I have 92 objects and want them to paginate by 5 per page. That's 19 pages where the last page contains 2 objects. Why doesn't it raise EmptyPage or InvalidPage exception if page is greater than 19? page = int(request.GET.get('page')) paginator = Paginator(self.get_queryset(), self.paginate_by, allow_empty_first_page=False) try: page = paginator.get_page(page) reports = list(page.object_list) except (EmptyPage, InvalidPage) as _error: reports = [] -
Django - Updating value only for the last item of list
This is how my ToDoapp looks like The date change works only for the last item in the list but for other items it throws the error: ValidationError at / ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] I see that irrespective of "Update" button I press, it passes only the last item's id and date. Find my code below: Index.html {% extends 'base.html' %} {% block content %} <h3 style = "margin-bottom: 20px"><strong>To Do List App</strong></h3> <form method="POST"> {%csrf_token%} <ul class="list-group"> {% for task in tasklist %} <li class="list-group-item d-flex justify-content-between align-items-center"> <input type='hidden' name = 'task_id' value='{{task.id}}'>{{task.tasks}} <span class="badge bg-primary rounded-pill">{{task.duedate}} <input type="date" name="datepick" /> <input type='submit' value ='Update'> </span> </li> {% endfor %} </form> Views.py def index(request): if request.method == "POST": task_id = request.POST.get('task_id') task=Task.objects.get(id=task_id) datepick = request.POST.get('datepick') task.duedate = datepick task.save() tasklist = Task.objects.all() return render(request, 'index.html', {'tasklist':tasklist}) I feel that mistake is in the HTML file and I'm not familiar with HTML. -
How to change ckeditor label
Do you know how to delete/change this ckeditor label? html <p> <label for="id_ckeditor_upload_field">Ckeditor upload field:</label> </p> -
how to call python class function [closed]
I created a custom class for error handling. this is a class. class APIResult(object): def __init__(self, response=False, return_code='', result={}, massage='', status=500): self.response = response self.return_code = return_code self.result = result self.massage = massage self.status = status def to_json(self): return Response({'response': self.response, 'return_code': self.return_code, 'result': self.result, 'massage': self.massage}, status=self.status) Input cls_obj = APIResult(False, 400, "registration_update_failed", errors["email_exist"], status.HTTP_400_BAD_REQUEST) return cls_obj.to_json() now I want to return to_json function. without calling from in input like that below. return APIResult(False, 400, "registration_update_failed", errors["email_exist"], status.HTTP_400_BAD_REQUEST) -
Is it necessary to assign a default value in model field?
As I know in Django, it requires the user to determine the default value for models fields. Like: class Student(models.Model): """Student info""" id = models.CharField( max_length=7,primary_key=True,default =-1) name = models.CharField(_('name'),max_length=8, default="x"); But I'm really annoyed at this. I just don't know what values have to be assgind in the first place. User should make the decision. Can I just Give None as the default value? What might be consequences? NPE? Give a random value. Is it specific to give a default value to the model field in Django? Or it's general to most MVC web frameworks. Or it's because of the database consideration? Thanks -
Django dynamically form
I have the following My models: # База товаров / Base products class Products(models.Model): name = models.CharField(max_length=150, verbose_name='Название') def __str__(self): return self.name class Meta: ordering = ('name',) verbose_name = 'База товаров' verbose_name_plural = 'База товаров' # Закупили / Base purchases class Purchases_item(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE, verbose_name='Товар') quantity = models.PositiveIntegerField(default=0, verbose_name='Кол-во') untils = models.ForeignKey(Untils, on_delete=models.CASCADE, verbose_name='Ед. измерения') price = models.DecimalField(max_digits=150, default=0, decimal_places=0, verbose_name='Цена себестоимости') total_price = models.DecimalField(max_digits=150, default=0, decimal_places=0, verbose_name='Общая сумма') def __str__(self): return str(self.product) def save(self, *args, **kwargs): super(Purchases_item, self).save(*args, **kwargs) val = self.price * self.quantity if self.total_price != val: self.total_price = self.price * self.quantity self.save() class Meta: ordering = ('product', 'price', 'total_price') verbose_name = 'Покупка по позициям' verbose_name_plural = 'Покупки по позициям' # Список который мы закупили записываем на склад / Purchases List # По факту это склад списком class Purchases(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, verbose_name='Дата') # переделать на defaul и отключить auto now add company = models.CharField(max_length=150, verbose_name='Компания', null=True, blank=True, default=None) product = models.ManyToManyField(Purchases_item, verbose_name='Товар(ы)') total_price = models.DecimalField(max_digits=150, decimal_places=0, verbose_name='Общая сумма', default=0) def __str__(self): return self.company def save(self, *args, **kwargs): super(Purchases, self).save(*args, **kwargs) if self.total_price != sum(product.total_price for product in self.product.all()): self.total_price = sum(product.total_price for product in self.product.all()) self.save() class Meta: ordering = ('date', … -
CommandError: No fixture named 'fixture' found
I'm trying to use loaddata to load some fixtures into a Django 2.2.10 project. According to the documentation, the command should look like this: python manage.py loaddata fixture app/fixtures/*.json However, when I run this command I get the following error: CommandError: No fixture named 'fixture' found. I figured the word "fixture" was being interpreted as a path to the fixture, so I removed it and it worked: python manage.py loaddata fixture app/fixtures/*.json I still find it weird though that the documentation tells me to do something that doesn't work. Am I missing something? I'm worried that I might have something wrong in my setup that is going to come back to haunt me in the future. -
ImportError: cannot import name 'Celery' from 'celery'
ImportError: cannot import name 'Celery' from 'celery' The code is running fine in my local machine. when i run this code on azure server then create this issue. here below is my project file structure in below screenshot. __init__.py file: from __future__ import absolute_import from core.celery import app as celery_app __all__ = ['celery_app'] celery.py file: from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') app = Celery('core') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) task.py file: from celery import shared_task from time import sleep from azure.datalake.store import core, lib, multithread from django.core.mail import send_mail token = lib.auth() adls_client = core.AzureDLFileSystem(token, store_name='bnlweda04d3232gsdfs') @shared_task def sleepy(duration): sleep(duration) return None @shared_task def send_email_task(subject,message,from_email,recipient_email,fail_silently): sleep(30) send_mail( subject,message,from_email,recipient_email,fail_silently ) return 'Mail sent success' I'm using celery version: 4.4.0 and python version: 3.8.10 -
How to convert drop down choice column to text field in Django forms
I am trying to make patient registration form in my project where Django automatically gives drop down choice list for the foreign key columns. How do I make that column into a text field as I need user to enter patient id instead of choosing from the long drop down list. I tried something but it didn't work for me. Please help if possible. from django import forms from HMSapp.models import Registration from django.core.exceptions import ValidationError class RegistrationForm(forms.ModelForm): Pid=forms.CharField() class Meta: model=Registration fields='__all__' def clean_Pid(self): patient_id=self.cleaned_data['Pid'] try: Pid=Registration.objects.get(id=patient_id) return Pid except: raise ValidationError('Patient id does not exist') -
Can't display foreign key related object in Django DetailView
I've got a booking class which is related to Customer and Barber models. I can display all bookings using the detail view, however, can't figure out how to display a booking/bookings that a specific barber has. Basically, I want to get a booking or multiple bookings of a barber based on the ID given to the url. Here is my model: customer_id = models.ForeignKey(User, on_delete = models.CASCADE,) barber_id = models.ForeignKey(Barber, on_delete = models.CASCADE) timeslot = models.DateTimeField('appointment') def __str__(self): return f"{self.customer_id} {self.barber_id} {self.timeslot}" def get_absolute_url(self): return reverse("model_detail", kwargs={"pk": self.pk}) My view: class GetBarberBooking(DetailView): model = Booking template_name = "barber_booking.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['barber'] = Booking.objects.filter( id=self.kwargs.get('<str:pk')) return context My url path: path('barber-booking/<str:pk>/', views.GetBarberBooking.as_view(), name='barber-booking'), -
Django migrations with Docker compose and volumes
I am using Django with Docker compose and all the persistent files are saved in a volume. My issue is that I am also saving my database in the volume: how does this influence migrations? I've added an new schema and there seems no way to reflect this change in the DB. When I apply the migrations on my local environment, it works, the migrations are correctly applied and I can see the new db schema, but this is because I've created a local folder app/static, which reflects the volume name of the docker-compose. Now, since the db is in that folder, it works, as the migrations are applied to the db. When I deploy my application, the db inside of the app/static remains the same old db, with the same old entries and the same old schemas. How can I apply the migrations so that the db inside of the volume app/static reflects the new changes, without losing the old entries? As a practical example I have added a new model Action, which is not existent on the server. So the DB has all the schemas but Action. Locally, I run makemigrations and migrate, producing the migration files (which … -
Why is Chart.js not rendering? Error: Uncaught ReferenceError: Chart is not defined
I am trying to implement chart.js in my django project, and I am starting with the example graph used on the chart.js website, before then amending the data and tweaking it. However, I can't yet get the default chart to pull through, and keep getting the error message: Uncaught ReferenceError: Chart is not defined This makes me think that the library isn't installed correctly, but I have used a few different CDNs and can't get it to work, any help would be much appreciated! html template: {% extends 'base.html' %} {% load static %} {% block content %} <canvas id="myChart" width="400" height="400"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Weight', 'Run Distance', 'Run Time', 'Date'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { y: … -
Django - ckeditor disappears after adding youtube plugin
I am trying to build a blog webpage and also i want to share my youtube tutorials in my page so i need this plugin so much. when i add this plugin to my project, ckeditor disappears. Can somebody help me to fix this? models.py class Makale(models.Model): kategori = models.ForeignKey(Kategori, on_delete=models.SET_NULL, null=True) # altKategori = models.ManyToManyField(AltKategori) baslik = models.CharField(max_length=50) kisaIcerik = models.TextField(max_length=300) tamIcerik = RichTextField(external_plugin_resources = [( 'youtube', '/static/ckeditor/ckeditor/plugins/youtube/', 'plugin.js', )]) settings.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'toolbar_Custom' : [ ['Bold', 'CodeSnippet', 'Font', 'FontSize', 'TextColor', 'BGColor', 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', 'Italic', 'Underline', 'Link', 'Unlink', 'RemoveFormat', 'Source', 'Image', 'Youtube'] ], 'extraPlugins' : ','.join(['codesnippet', 'youtube']), 'width': 'auto', }, } when i remove youtube plugin from ckeditor_configs on settings.py it works perfect. The problem is on Youtube plugin. I don't know how to fix that. -
Test doesn't remove generated files using factory_boy in django
I'm using factory_boy to generate arbitrary data to run tests. but after each test it doesn't delete files automatically. Is there anything I should add? Any suggestion is highly appreciated Model for test class TrackFactory(factory.django.DjangoModelFactory): class Meta: model = "tracks.Track" id = factory.Faker("uuid4") filename = "Track 01 - track" created_by = factory.SubFactory(UserFactory) file = factory.django.FileField(filename="test.mp3") track_length = 145 @classmethod def _create(cls, model_class, *args, **kwargs): instance = cls.build(*args, **kwargs) instance.save() return instance Test class TestViewDeleteTrack(AuthorizedApiTestCase): def setUp(self): self.url = reverse(list-track) self.user_data = UserFactory() self.data = TrackFactory(created_by=self.user_data) self.client.force_authenticate(user=self.user_data) def test_list_tracks(self): self.get_and_assert_equal_status_code(status.HTTP_200_OK) def test_delete_track_valid_pk(self): self.delete_and_assert_equal_status_code( "delete-track", self.data.pk, status.HTTP_204_NO_CONTENT, ) custom methods for testing used above def get_and_assert_equal_status_code(self, status_code): response = self.client.get(self.url) self.assertEqual(response.status_code, status_code) return response def delete_and_assert_equal_status_code(self, url_name, pk, status_code): url = reverse(url_name, kwargs={"pk": pk}) response = self.client.delete(url) self.assertEqual(response.status_code, status_code) -
Heroku project deploy issue
I have 2 projects made on django. I tried to deploy both of them to Heroku, but every time i'm trying - i'm getting an error like this: -----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed (It's the situation when i choose a heroku/python as project buildpack) Another one occurs when i try to deploy project without selected buildpack: -----> Building on the Heroku-22 stack -----> Determining which buildpack to use for this app ! No default language could be detected for this app. HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. See https://devcenter.heroku.com/articles/buildpacks ! Push failed In both variants i use "Deploy method: GitHub repo". You can check out one of my projects here: https://github.com/Fakemrx/Train-Travel-Project All information about my issue i found yet is that i need to have some "special" files in project folder (not in subfolders!) that will mean for Heroku tha it's python project. I already tried to use third-party builpacks but got no results. *I'm trying to deploy my project not from command prompt, but from Deploy menu on Heroku (https://dashboard.heroku.com/apps/some-custom-app-name/deploy/github). -
How can i display the category for a particular product in the product list page? - Django
I am trying to display a product list page with products attributes along with category which is a MPTT field. I want to display the category assigned to that particular product in the product list page. How can i achieve this? Models class Category(MPTTModel): """ Inventory Category table implimented with MPTT """ name = models.CharField( max_length=100, null=False, unique=False, blank=False, verbose_name=_("category name"), help_text=_("format: required, max-100"), ) slug = AutoSlugField(populate_from='name') cat_img = models.ImageField(upload_to='images/categories/') parent = TreeForeignKey( "self", on_delete=models.PROTECT, related_name="children", null=True, blank=True, unique=False, verbose_name=_("parent of category"), help_text=_("format: not required"), ) class MPTTMeta: order_insertion_by = ["name"] class Meta: verbose_name = _("product category") verbose_name_plural = _("product categories") def __str__(self): return self.name class Product(models.Model): """ Product details table """ product_id = models.UUIDField(default=uuid.uuid4, editable=False) sku = models.CharField(max_length=255, blank=True, null=True) name = models.CharField( max_length=255, unique=False, null=False, blank=False, verbose_name=_("product name"), help_text=_("format: required, max-255"), ) slug = AutoSlugField(populate_from='name') price = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) description = models.TextField( unique=False, null=True, blank=True, verbose_name=_("product description"), help_text=_("format: required"), ) prd_img = models.ImageField(upload_to='images/products/', null=True, blank=True) category = TreeManyToManyField(Category, null=True, blank=True) modifier_group = models.ManyToManyField(ModifierGroup, null=True, blank=True) def __str__(self): return self.name Views @login_required(login_url='/login/') def productList(request): products = Product.objects.all() context = {'products':products} template = 'product/product/products.html' return render(request,template,context) Template <td class="text-end pe-0" data-order="37"> <span class="fw-bold ms-3">{{product.category.name}}</span> </td> Template Result … -
Alter primart key in django model, must start with 1001
I am working on a project, in which we have requirement that we have to start our primary key by 1001. The framework used is Django here. So, we have to create a migration having id as alter field. But I don't know how to alter sequence of primary key. From some articles, I use auto_increment but it gives error of undefined. Thanks -
Multiple files in a single field model of Django
I am making a site in which user uploads it's pdf and back of the site we generate audio file for each page and now we want to save it on the database(mysql). Now the problem starts we have model in django and model have the fields which are for a single input. for example class Info(models.Model): phone_img = models.ImageField(upload_to='pics') Name = models.CharField(max_length=70) RAM = models.IntegerField(default= None) ROM = models.IntegerField(default= None) Cost = models.IntegerField(default= None) Link = models.URLField(max_length=250) Now if we use models.FileField(upload_to='files') then it will upload files to a files folder but I have several files then how to upload that files, because we can't create fields for that and if we create fields for that then it's not fix that the user uploaded pdf have the same no. of pages as we have fields. -
ModuleNotFoundError: No module named 'myApp' deploying django on planethoster with n0c
I'm struggling with n0c and wsgi (with passenger), it works in developpment but not while deploying The error message /opt/passenger/src/helper-scripts/wsgi-loader.py:26: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses import sys, os, io, re, imp, threading, signal, traceback, socket, select, struct, logging, errno Traceback (most recent call last): File "/opt/passenger/src/helper-scripts/wsgi-loader.py", line 369, in <module> app_module = load_app() File "/opt/passenger/src/helper-scripts/wsgi-loader.py", line 76, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/opt/alt/python310/lib64/python3.10/imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 719, in _load File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/ambnvnpa/kriill/passenger_wsgi.py", line 1, in <module> import kriill.src.kriill.wsgi File "/home/ambnvnpa/kriill/kriill/src/kriill/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/ambnvnpa/virtualenv/kriill/3.10/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/ambnvnpa/virtualenv/kriill/3.10/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ambnvnpa/virtualenv/kriill/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ambnvnpa/virtualenv/kriill/3.10/lib/python3.10/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/opt/alt/python310/lib64/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'home' passenger_wsgi.py I added the multiple dots at the difference of the tutorial (https://kb.planethoster.com/guide/astuces-techniques/installer-django-sur-world/) because of my folder architecture. import kriill.src.kriill.wsgi … -
How to use Django backend templet variable in JS
I want to use backend data in the js file. return render(request, "class.html", {'all_classes':all_class}) I want to use it in the JS 'all_classes'. I know for the HTML - <select name="subject_class" type="text" class="form-control" required > {% for class in all_classes %} <option value="{{ class.class_name }}">{{ class.class_name }}</option> {% endfor %} </select> but please give me an idea for the javascript. -
Get all tags, if post has tags then mark as selected and remaining as not selected in django
While editing post to update i'm getting only selected tags for that post, how can i get all tags and with selected option for particular post. For example i have 4 tags and 1 tag is assigned to a post, when i edit that post to update i should get assigned tag as selected and remaining 3 tags as not selected. so that i can assign remaining tags to post if i wanted. And is there any way that i can create extra tags while updating post. For reference i've uploaded image below in that i got only selected tag i want to show remaining non selected tags also. models.py class Tag(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Card(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=150, unique=True) desc = models.TextField() img = models.ImageField(upload_to='uploads/') date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) publish_date = models.DateTimeField(blank=True, null=True) published = models.BooleanField(default=False) tags = models.ManyToManyField(Tag, blank=True) def __str__(self): return self.title views.py @login_required(login_url = '/login/') def edit(request, pk): edit_list = Card.objects.get(id=pk) edit_tags = Card.objects.filter(id=pk) tag = Tag.objects.all() context = { 'edit_list': edit_list, 'edit_tags': edit_tags, 'tag':tag, } return render(request, 'edit-post.html', context) HTML <div class="container my-5"> <form action="{% url 'post_update' edit_list.pk %}" method="post" enctype="multipart/form-data">{% csrf_token %} <div … -
Signifianct Reduction in Performance after Installing Whitenoise
I installed and configured whitenoise to compress my static files, after which I ran collectstatic, and it appears everything ran successfully. It says 598 files have been post-processed. However, my CSS files are still the same size, and page load times have increased in production but are the same in development. Lighthouse scores have decreased from 95 to 87 after repeated tests. I must have configured something wrong, but I'm not sure what. Settings that probably aren't relevant have been removed for brevity. Settings.py # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv("DEBUG", "True") == "True" if DEBUG is True: ALLOWED_HOSTS = [] DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic': if os.getenv("DATABASE_URL", None) is None: raise Exception("DATABASE_URL environment variable not defined") DATABASES = { "default": dj_database_url.parse(os.environ.get("DATABASE_URL")), } # HTTPS Settings SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True # HSTS Settings SECURE_HSTS_SECONDS = 31536000 # 1 year SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', …