Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make django publish messages to mqtt on views?
I am trying to integrate paho.mqtt into django to publish msgs to mosquitto broker, I have searched but I havent found much tutorials on how I can achieve it. Well i tried to put this code into mqtt.py: from paho.mqtt import client as mqtt_client topic = "#topic#" def connect_mqtt() -> mqtt_client: def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(topic) client.username_pw_set('#username#', '#psswd#') client.on_connect = on_connect client.connect('####the host##', 1883) return client def publish(client): msg = 'test test' result = client.publish(topic, msg) def run(): client = connect_mqtt() publish(client) client.loop_forever() and in init.py from . import mqtt client.loop_start() and when I call run() on views it doesn't work, and runserver it doesn't seem like the right way to do it. Can somebody explain to me how should I structure my files and system to do it right. Please any help would be much appreciated. -
Django Project works on local but not on heroku
If I try to run the server on local it works without errors but when trying to run it with heroku I get 2021-08-24T23:55:05.395710+00:00 app[web.1]: Internal Server Error: / 2021-08-24T23:55:05.395718+00:00 app[web.1]: Traceback (most recent call last): 2021-08-24T23:55:05.395719+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute 2021-08-24T23:55:05.395720+00:00 app[web.1]: return self.cursor.execute(sql, params) 2021-08-24T23:55:05.395720+00:00 app[web.1]: psycopg2.errors.UndefinedTable: relation "main_chapter" does not exist 2021-08-24T23:55:05.395721+00:00 app[web.1]: LINE 1: ...er_text", "main_chapter"."chapter_footnotes" FROM "main_chap... 2021-08-24T23:55:05.395722+00:00 app[web.1]: ^ 2021-08-24T23:55:05.395723+00:00 app[web.1]: 2021-08-24T23:55:05.395723+00:00 app[web.1]: 2021-08-24T23:55:05.395723+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2021-08-24T23:55:05.395724+00:00 app[web.1]: 2021-08-24T23:55:05.395724+00:00 app[web.1]: Traceback (most recent call last): 2021-08-24T23:55:05.395724+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner 2021-08-24T23:55:05.395725+00:00 app[web.1]: response = get_response(request) 2021-08-24T23:55:05.395725+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response 2021-08-24T23:55:05.395726+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2021-08-24T23:55:05.395726+00:00 app[web.1]: File "/app/main/views.py", line 10, in home 2021-08-24T23:55:05.395726+00:00 app[web.1]: last = chapter_list.last() 2021-08-24T23:55:05.395727+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 679, in last 2021-08-24T23:55:05.395727+00:00 app[web.1]: for obj in (self.reverse() if self.ordered else self.order_by('-pk'))[:1]: 2021-08-24T23:55:05.395727+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 280, in __iter__ 2021-08-24T23:55:05.395728+00:00 app[web.1]: self._fetch_all() 2021-08-24T23:55:05.395728+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all 2021-08-24T23:55:05.395728+00:00 app[web.1]: self._result_cache = list(self._iterable_class(self)) 2021-08-24T23:55:05.395729+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ 2021-08-24T23:55:05.395729+00:00 app[web.1]: results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) 2021-08-24T23:55:05.395729+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql 2021-08-24T23:55:05.395730+00:00 … -
Django's password reset URL customized isn't loading after the first try
I'm using Django's password-reset URLs and I have created my own templates for them, but after I put in my Email address it redirects me to the default templates instead of redirecting me to my custom template. urls.py path('password_reset/', auth_views.PasswordResetView.as_view(template_name="authsystem/password_reset.html"), name='password_reset'), path('password_reset/done', auth_views.PasswordResetDoneView.as_view(template_name="authsystem/password_reset_sent.html"), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="authsystem/password_reset_form.html"), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name="authsystem/password_reset_done.html"), name='password_reset_complete'), After It moves from 'password_reset.html' it's supposed to render 'password_reset_sent.html' but it renders Django's default template. -
i cant submit integer field in django Rest Framework ? TypeError 'BoundField' object is not iterable
this is my views.py class ClinicList(ListCreateAPIView): serializer_class=CliniDetailcSerializer permission_classes=[IsAuthenticatedOrReadOnly] def get_queryset(self): qs=Clinic.objects.all().order_by('-id') return qs def post(self,request,format=None): if request.user.is_authenticated and request.user.profile.type == 'doctor': serializer = CliniDetailcSerializer(data=request.data) if serializer.is_valid(): print(serializer.data.values()) Clinic.objects.create(doctor=request.user.profile,name=serializer["name"],price=serializer.data["price"],days=serializer["days"],start_time=serializer["start_time"],end_time=serializer["end_time"]) context={"data":serializer.data,"message":"clinic added successffullt"} return Response(serializer.data) else: return Response({"message": "invalid data"}) else: return Response({"message": "your are not a doctor"}) and i got this error when i submit: 'BoundField' object is not iterable -
2026, SSL connection error: unknown error number - encountered by my django app after upgrading mysql from 5 to 8
I upgraded mysql from 5.7 to 8.0 and started encountering this error which is preventing my app from connecting to the database. django.db.utils.OperationalError: (2026, 'SSL connection error: unknown error number') I have my own ca.pem server-cert.pem server-key.pem which mysql uses. The django app properly sets the ca cert in settings. Everything works in 5.7. -
Django Admin make field editable for specific user group
Lets say i have two user groups (user, admin) in my application. Both can see the fields of an instance on the admin model. I have a field named "approved" which is a boolean field. The admin should be able to edit this field, but for the user it should be a read-only field. I tried to use the get_readonly_fields method from django, but it doesent seem to work in combination with the list_display and list_editable attributes. My approach looks like this: @admin.register(Component) class ComponentAdmin(admin.ModelAdmin): exclude = ("created_by",) list_display = ( "id", "approved" ) list_editable = ("approved") def get_readonly_fields(self, request, obj=None): if is_admin_or_mod(request): return [] return ["approved"] -
Django - custom getter for 1 field in model
I am writing a model for an external Oracle DB, which I need to pull info from to my project. One of the fields in that Oracle DB is an XMLType, and it hosts large portion of data, which needs to be pulled via .getClobVal() method, instead of querying it straight as it is. I was wondering, if Django supports any sort of custom logic, for Model's specific fields. Something along the lines of a getter for each field, which I could overwrite to query that specific field as XMLType.getClobVal() instead of just XMLType. At the same time, I don`t want to touch the logic for querying the rest of the Model's fields. Any ideas? -
How to use django-taggit in a template?
I want to list articles by tag to have the title of the tag in the title and the titles of the articles in the list. My view.py looks like this: from taggit.models import TaggedItem class ArticlesByTagsList(ListView): template_name = 'articles/articles_by_tags.html' context_object_name = 'articles_list' def get_queryset(self): return TaggedItem.objects.filter(tag=self.kwargs['tag']) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tags_list'] = Tag.objects.all() return context My articles_by_tags.html template looks like this: {% block content %} <h1>Список публикаций {{ articles_list.item }}</h1> {% for item in articles_list %} <h2>{{ item }}</h2> {% endfor %} {% endblock %} I end up with the following output:ArticlesByTagsList.as_view() result How can I solve this problem? -
Pytest failed when testing API with correct URL and data
When I am creating a Clinic via Swagger or Postman it works fine and field with the same data when test it ! model class Clinic(models.Model): name = models.CharField(max_length=50) price = models.FloatField() doctor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='doctor_clinic') date = models.ManyToManyField(ClinicDate, related_name='clinic_date') serializer class ClinicDateSerializers(serializers.ModelSerializer): class Meta: model = ClinicDate fields = ['day','start_time', 'end_time'] class ClinicSerializers(serializers.ModelSerializer): doctor = serializers.StringRelatedField(required=False) date = ClinicDateSerializers(many=True, required=True) class Meta: model = Clinic fields = ['name', 'price', 'doctor', 'date'] def create(self, validated_data): dates_data = validated_data.pop('date') user = self.context['request'].user clinic = Clinic.objects.create(doctor=user, **validated_data) for date_data in dates_data: dt = ClinicDate.objects.create(**date_data) clinic.date.add(dt) return clinic URL path('add/', views.ClinicCreateView.as_view(), name='clinic-create'), pytest @pytest.mark.django_db class TestClinic: @pytest.fixture def setup(self): User.objects.create_doctor(email="doctor1@doctoronline.com", password="12345") data = { 'email':'doctor1@doctoronline.com', 'password':'12345', } response = client.post(reverse('token_obtain_pair_doctor'), data=data) self.access_token = response.json()['access'] client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.access_token) def test_valid_create_clinic(self, setup): data = { "name": "Clinic 1", "price": 1000, "date": [ { "day": "SATURDAY", "start_time": "2021-08-24T21:21:17.960Z", "end_time": "2021-08-24T21:21:17.960Z" } ] } response = client.post(reverse('clinic-create'), data=data) assert response.status_code == status.HTTP_201_CREATED Hint there is no problem with setup or data -
error on calling a django rest framework endpoint from the same server
I have an API endpoint let's say sampleapi.domain.com/api/v1/1 that worked well in development, both locally (127.0.0.1) and online sampleapi-dev.domain.com, but when I call the same endpoint sampleapi.domain.com/api/v1/1 from the server from which the call is being made sampleapi.domain.com, I get json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) which is unusual since the same code works in development and online. When I changed how I'm starting gunicorn from gunicorn --certfile=crt --keyfile=key --bind 0.0.0.0:8000 a.wsgi to gunicorn --certfile=crt --keyfile=key --bind 0.0.0.0:8000 a.wsgi -w 1 --threads 2 This seems to solve the error, but I'm not entirely sure why that is the case. Was it that the single thread was not available to call the API because it was busy loading the page the API is on? If this isn't the reason, what could be the reason? -
Django displaying 2 tables side by side
As the title says, i'm trying to display 2 tables side by side. I tried a couple of methods but no one shows results. Right now this is the code of the 2 tables: <div> <table style="float: left" class="table table-striped table-bordered table-sm"> {% for item in product %} {% if item.orden_ref_id == orden.id %} <tr> <td> {{ item.articulo }} </td> </tr> {% endif %} {% endfor %} </table> <table style="float: right" class="table table-striped table-bordered table-sm"> {% for item in valor %} {% if item.refer_id == orden.id %} {% if item.show_ref == '2' %} <tr> <td> {{ item.costo }} </td> </tr> {% endif %} {% endif %} {% endfor %} </table> </div> but it look like this: Tables look How can i solve this issue? -
Django Deployment in Local network
I have a Django application to deploy on my company's server (local network). I asked to create a Virtual Machine (Windows), my questions are: 1- which is good for deployment, Windows or Linux VM? 2- Do I need to use any other software like Apache webserver or just I can run my Django server? 3- Is there anything I should do? All my best -
How to set up your python django project on godaddy
I have a complete project built with python django and I need to host it on GoDaddy. But in the cPanel File Manager there is so many folders inside and I don't know where to put my Django project. I searched up in the net and only found people using different hosting companies. Where do I put the files? cPanel File Manager I have a domain already and I connected it to the hosting. Django Project Looks Like -
Django Rest Framework Django Filters ModelMultipleChoiceFilter doesn't work with icontains
I'm trying to filter Django permission groups by the permissions within the group which has a ManyToMany relationship. I'm using django == 3.2.5, django_filter == 2.4.0 and django_rest_framework==3.12.4. Currently the filter only works if I use "exact" as my field lookup but when I use "icontains" it throws this error; { "permissions__icontains": [ "“can” is not a valid value." ], I can't see what I'm doing differently versus from docs and this stack overflow post. https://django-filter.readthedocs.io/en/stable/ref/filters.html?highlight=ModelMultipleChoiceFilter#modelmultiplechoicefilter How to use ModelMultipleChoiceFilter? Is there a way I can get filter results when it is not an exact match?? cheers in advance! request url http://127.0.0.1:8000/permission_groups/?permissions__icontains=can filter class PermissionsGroupFilterSet(FilterSet): name = AllValuesMultipleFilter(field_name="name") permissions = ModelMultipleChoiceFilter( queryset=Permission.objects.all(), field_name="permissions__name", to_field_name="name" ) class Meta: model = Group fields = { "name": ["icontains", "in"], "permissions": ["exact", "icontains"], } models.py (standard group/permission models) class Group(models.Model): name = models.CharField(_('name'), max_length=150, unique=True) permissions = models.ManyToManyField( Permission, verbose_name=_('permissions'), blank=True, ) objects = GroupManager() class Meta: verbose_name = _('group') verbose_name_plural = _('groups') def __str__(self): return self.name def natural_key(self): return (self.name,) class Permission(models.Model): name = models.CharField(_('name'), max_length=255) content_type = models.ForeignKey( ContentType, models.CASCADE, verbose_name=_('content type'), ) codename = models.CharField(_('codename'), max_length=100) objects = PermissionManager() class Meta: verbose_name = _('permission') verbose_name_plural = _('permissions') unique_together = [['content_type', 'codename']] … -
Saving an object with formset element AND making a copy with new related elements
I'm trying to do some kind of a mixte between a Create and an Update on an object that has foreign keys (managed as inline formset). Updating the parent object in a form (as well as its related formset forms) works fine. I can also save a copy of that parent object as a new instance in the DB, that works fine. However I can't seem to figure out how to also make copy of the formset as new independant objects. Basically, once all is said & done, I want: Foo (pk=1) bar_1 bar_2 ... bar_n FooCopy (pk=2) bar_1_copy ... bar_n_copy I currently can modify Foo, create FooCopy, as well as modify bar_1 to bar_n... but cannot create bar_1_copy etc. For instance: class SoumissionUpdateView(LoginRequiredMixin, SideBarMixin, UpdateView): def form_valid(self, form, formset): # that saves any modification to the initial object, as well as the elements in the formset self.object = form.save() formset.instance = self.object formset.save() # this saves the parent object as a new instance. However no new formset objects are created in the db. self.object.pk = None self.object.save() formset.instance = self.object formset.save() # since those should be 2 different sets of instance in db return HttpResponseRedirect(self.get_success_url()) My understanding was since … -
Filtering field in a django form
I am building a website with django. This website is user based and each user has a profile model. Right now, I am working on building a system where each user can input their job experience. I want it so that you can input a category, and then fill out points for each category. (For example, if you wrote for the New York Times, the category would be "New York Times" and then right under it would be the articles you wrote in bullet points). I can create a category. I can create a work and then assign the work to a category. The issue I am having is that a user can choose a category from a different user in the work form. All I want to do is make it so that the field "category" is filtered so that users can only select categories that they made. I have tried a couple of things but I am not sure where is the best place to filter this field. models.py from django.db import models from django.contrib.auth.models import User class Category(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='cat') name = models.CharField(max_length=100) date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) def __str__(self): return … -
AttributeError: 'InMemoryUploadedFile' object has no attribute 'decode'
I am building a django application where I upload a folder containing a lot of CSV files. I retrieve the folder like this in HTML and it works fine: <div class="upload_csv"> <h2>Upload</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="file" name="folder" multiple="true" webkitdirectory="true" directory="true"/> <button type="submit">Upload</button> </div> Now, the problem is that I need to use "utf-8" encoding before moving on. I dont know how to do that when handling a directory, and not only an UploadedFile file. What I have so far is this: def csv_retriever(request): if request.method == 'POST' and request.FILES['folder']: # encoding could happen here with the entire folder for file in request.FILES.getlist('folder'): # or here with the current file calculations(file) return render(request, 'price_calculator_started.html') -
json decode error expecting value: line 1 column 1 (char 0)
I am trying to get an mpesa authentication token which is json format. It gives an error in the decoding code Below is my views.py import requests import json def getAccessToken(request): consumer_key = '' consumer_secret = '' api_URL = 'https://sandbox.safaricom.co.ke/oauth/v1/generate? grant_type=client_credentials' r = requests.get(api_URL, auth=HTTPBasicAuth(consumer_key, consumer_secret)) mpesa_access_token = json.loads(r.text) validated_mpesa_access_token = mpesa_access_token['access_token'] return HttpResponse(validated_mpesa_access_token) Below is my projects urls.py from django.urls import path, include urlpatterns = [ path('', include('store.urls')), ] where store is the name of my app My store urls.py, from django.urls import path from .import views urlpatterns = [ path('access/token/', views.getAccessToken, name='get_mpesa_access_token'), ] When I access that url instead of giving me the token I want, it gives the error below: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 24, 2021 - 20:45:26 Django version 2.2, using settings 'mvee.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: /access/token/ Traceback (most recent call last): File "/home/victor_nzioka/Desktop/projects/django2.2/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/victor_nzioka/Desktop/projects/django2.2/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/victor_nzioka/Desktop/projects/django2.2/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/victor_nzioka/Desktop/projects/venv/MVEE/src/store/views.py", line 121, in getAccessToken mpesa_access_token = json.loads(r.text) File "/home/victor_nzioka/anaconda3/lib/python3.8/json/__init__.py", … -
Django Model and Form for Comment system
I have made a comment system under my books where only the authenticated user can comment. When I use the form to add a comment, it doesn't work! why ? here is my models models.py class Books(models.Model): author = models.ManyToManyField(Authors) title = models.CharField(max_length=250) number_of_pages = models.PositiveIntegerField(validators=[MaxValueValidator(99999999999)]) date_added = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) publication_date = models.PositiveIntegerField(default=current_year(), validators=[MinValueValidator(300), max_value_current_year]) cover = models.ImageField(upload_to='pics/covers/', default='pics/default-cover.jpg') pdf_file = models.FileField(upload_to='pdfs/books/', default='pdfs/default-pdf.pdf') category = models.ForeignKey(Categories, on_delete=models.CASCADE) def __str__(self): return self.title class Comments(models.Model): book = models.ForeignKey(Books, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} - {}'.format(self.livre.title, self.user) here is my forms forms.py class BookForm(ModelForm): class Meta: model = Books fields = '__all__' class CommentForm(ModelForm): class Meta: model = Comments fields = ['body'] here is my views views.py @login_required(login_url='login') def book_detail_view(request, book_id): books = get_object_or_404(Books, pk=book_id) context = {'books': books,} return render(request, 'book_detail.html', context) @login_required(login_url='login') def add_comment(request, comment_id): form = CommentForm() books = get_object_or_404(Books, pk=comment_id) user = request.user if request.method == "POST": form = CommentForm(request.POST, instance=books) if form.is_valid(): comment = form.save(commit=False) comment.user = user comment.books = books comment.save() return redirect('book_detail', books.id) context = {'form': form} return render(request, 'comment_form.html', context) here is my book detail page book_detail.html {% extends 'base.html' %} {% block … -
Input data in german data format combined with ChartsJs
I'm relative new to Charts.js, but I'll need it to create some nice graphs for my webpage. In the background I have a Django project running which computes me a certain amount of numbers. Since I've put the language code in Django to "de-at" (requirement, since there are some input variables to fill in by austrian users), the number formats are done like: "1.000.000,54€" and not the US-way like "1,000,000.54€". If I now want to add some of my data into charts.js, it won't read the data, which has more than 6 digits. Furthermore, if there is a number like "653.598,36" it takes actually two parameters, namely (653,598 ; 36). Formatting the numbers in python does not help, since charts.js won't use strings for the graphs. Using the setting "locale = 'de-DE'" in the charts.js options only helps for labelling propertes, not for the data itself. If I change the Django setting back to "en-us", charts.js works with the numbers, but than my numbers on the webpage are not formatted correctly for the end-user. Has someone experienced this problem and has a solution to it? Thank you and best regards! Here is the code of charts.js with example values. I … -
How to add items drop down menu in django
I'm making a web app for post blogs.And I added categories field to identify the category of that blog.But the problem is I can add categories in only when I on admin page.But I want to have that add category button in fronend as well. example: when I click categories field it shows up current categories in database but I want to add add button to that drop down menu of category. .this is picture of my add post page model.py class PostForm(forms.ModelForm): category = forms.ModelChoiceField(queryset=category.objects.all().order_by('name')) class Meta: model = Post fields = ('title', 'category','author', 'content', 'image','status') template {% if user.is_authenticated %} <h1>Add Post...</h1> <br/><br/> <div class="form-group"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.media }} {{ form|crispy}} <br> <button class="btn btn-secondary btn-lg">Post</button> </form> -
AppRegistryNotReady Error when packaging a Django app with Pyinstaller
I'm using Django 3 (also tried with 2.2) and pyinstaller to make an standalone Django based app. I run pyinstaller this way: pyinstaller --onedir --clean --name=projectx manage.py --additional-hooks-dir=projectx_backend/ I have a custom hook with this code: from PyInstaller.utils.hooks import collect_submodules hiddenimports = collect_submodules('django.contrib') And an __init__.py file in my projectx_backend/settings folder with the following content: from .desktop import * The content of manage.py is: #!/usr/bin/env python import os import sys if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectx_backend.settings.desktop') import django from django.conf import settings from projectx_backend.settings import desktop settings.configure(default_settings=desktop) django.setup() try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) When trying to build the exec it complaints about some missing modules. I ensured those modules are installer in my current environment, but I think I'm not loading them correctly. pyinstaller --onedir --clean --name=projectx manage.py --additional-hooks-dir=projectx_backend/ 39 INFO: PyInstaller: 4.3 39 INFO: Python: 3.8.10 49 INFO: Platform: Linux-5.11.0-27-generic-x86_64-with-glibc2.29 49 INFO: wrote /home/peckers/dev/projectx-backend/projectx.spec 51 INFO: UPX is not available. 52 INFO: Removing temporary files and cleaning cache in /home/peckers/.cache/pyinstaller 53 INFO: Extending PYTHONPATH … -
UndefinedError: 'request' is undefined in template
I am using Django 3.1. I have a template view that usually renders fine, however on occasion I find the following error in my logs. Unfortunately I can't seem to reproduce it. UndefinedError: 'request' is undefined File "django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "django/core/handlers/base.py", line 106, in _get_response response = middleware_method(request, callback, callback_args, callback_kwargs) File "django/middleware/csrf.py", line 242, in process_view return self._reject(request, REASON_NO_REFERER) File "django/middleware/csrf.py", line 149, in _reject response = _get_failure_view()(request, reason=reason) File "django/views/csrf.py", line 154, in csrf_failure return HttpResponseForbidden(t.render(c), content_type='text/html') File "django_jinja/backend.py", line 59, in render return mark_safe(self._process_template(self.template.render, context, request)) File "django_jinja/backend.py", line 105, in _process_template return handler(context) File "scout_apm/instruments/jinja2.py", line 74, in wrapped_render return wrapped(*args, **kwargs) File "jinja2/environment.py", line 1090, in render self.environment.handle_exception() File "jinja2/environment.py", line 832, in handle_exception reraise(*rewrite_traceback_stack(source=source)) File "jinja2/_compat.py", line 28, in reraise raise value.with_traceback(tb) File "/app/templates/403_csrf.html", line 8, in top-level template code {% set card_body %} File "/app/templates/global/base_tenant.html", line 2, in top-level template code {% extends 'global/base.html' %} File "/app/templates/global/base.html", line 4, in top-level template code {% block header %} File "/app/templates/global/base.html", line 26, in block "header" <link nonce="{{ request.csp_nonce }}" rel="manifest" href="{{ static('manifest.json') }}"> File "jinja2/environment.py", line 471, in getattr return getattr(obj, attribute) This appears to be an issue … -
Need Django Query optimization (2 Queries instead of 21)
I have a Django project on EBS and one query takes a pretty long time. I'd like to optimize it so that it's just one or two queries but I'm not sure if it's even possible. Models: WebSite,Article The query is a list of Articles from different websites. WebSite model has a home_order and home_article_count attributes that are used to select a number of articles and in which order they are. Example for websites A, B and C: A - A.home_order = 2, A.home_article_count=3 B - B.home_order = 1, B.home_article_count=5 C - C.home_order = 3, C.home_article_count=7 The result would be (aA means an article from website A): aB,aB,aB,aB,aB,aA,aA,aA,aC,aC,aC,aC,aC,aC,aC The lists starts with aB that means articles from website B because B.home_order=1, there are 5 aB articles as B.home_article_count=5. Right now, this is a Manager method that returns the articles: def home(self) -> QuerySet: articles_pks = [] for ws in WebSite.objects.active().order_by('home_order', 'name'): articles_pks.extend(ws.articles.filter(is_active=True).order_by('-created')[:ws.home_article_count].values_list('pk',flat=True)) return self.get_queryset().filter(pk__in=articles_pks) That means, for 20 WebSite objects, there is 21 queries (one that gets the websites and the other 20 for articles). Is it possible to merge it into one or two queries while respecting the WebSite.home_order and WebSite.home_article_count? -
How to sort column with dates from sqlite3 django with js datatables
I'm have datetime.datetime data in sqlite database in format "2021-04-07 09:12:22". Web app on Django show me this like "7 апреля 2021 г. 09:12" ("7 April 2021 09:12"). And I'm cant find the right format date to apply sort in my table on page with JS Datatables. All script source load on HTML page. $(document).ready(function() { $.fn.dataTable.moment('YYYY-MM-DD HH:mm:ss'); $('#purchases').DataTable( { "iDisplayLength": 50, "order": [[ 2, "desc" ]] } ); } ); When i'm commented this $.fn.dataTable.moment('YYYY-MM-DD HH:mm:ss'); datatables render table very well. But with this => datatables is not work right (dont render table). Asking for help with right date format for sorting.