Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Advice on adding an ancestors ArrayField to a self-referential model in Django
I'm developing a Django app (Django 3.2.8, Python 3.9, PostgreSQL 13.4) that functions very much like an FTP service. For the folder/file structure I've created a self-referential model called "Instance", which also uses generic relations so that I can reuse/structure various content types under one another: class Instance(models.Model): parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') subscribers = models.ManyToManyField('users.Organization', blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') However, I'm finding that development is being limited/slowed by the need for raw CTE queries. And I'm thinking that the most elegant way (based on the views I require) to make this model fully ORM-accessible is to add an "ancestors" ArrayField. class Instance(models.Model): parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') ancestors = ArrayField(models.PositiveIntegerField(), null=True, blank=True, default=list) .... I was easily able to construct & add an array value to this field through my views/scripts with a function like: def get_ancestors(context_instance, ancestors_array): ancestors_array.append(context_instance.id) if context_instance.parent: return get_ancestors(context_instance.parent, ancestors_array) else: return list(reversed(ancestors_array)) However, I thought it would be far better to have the ancestors array value calculated and added whenever an instance of the "Instance" model was saved. I couldn't figure how it would be possible to query instances of a model … -
Django ValueError: too many values to unpack (expected 2)
I am a beginner on Django and I need help on my django 2.2 application. I have virtual machines and schedules with a manytomany relationship. I am trying to create a new schedule but I have an error. Basically in my schedule creation form in a column I display the list of VMs. So we can select which machine to assign a schedule. But what I would like is to display in another column the existing schedules, like this(Picture) :https://ibb.co/2dvTzXc I tried with a raw query, It's display well, but When I tried to send my form an error occured:My traceback = https://dpaste.org/p9SQ My models = https://dpaste.org/FwFe My code = https://dpaste.org/ZsNZ # MY TEMPLATE {% for i in form.vms.field.choices %} <tr class="clickable_vm"> <td> <label for="{{ i.0 }}"> <input type="checkbox" name="vms" value="{{ i.0 }}" class="displaynone" id="{{ i.0 }}">{{ i.1 }} </label> </td> <td class="schedule-name">{% for j in i.2 %}{{ j }}<br/>{% endfor %}</td> </tr> {% endfor %} # MY RAW QUERY cursor = connection.cursor() cursor.execute( ' SELECT vmware_virtualmachine.id,' ' vmware_virtualmachine.name,' ' group_concat( appli_vmschedule.schedule) as "schedule"' ' FROM vmware_virtualmachine' ' LEFT OUTER JOIN appli_vmschedule_vms' ' ON (vmware_virtualmachine.id = appli_vmschedule_vms.virtualmachine_id)' ' LEFT OUTER JOIN appli_vmschedule' ' ON (appli_vmschedule_vms.vmschedule_id = appli_vmschedule.id)' ' group by … -
Upgrading to django 3.2 breaks API tests (response.data['detail'])
I'm upgrading our django app from 3.0.5 to 3.2.9, and I'm having some issues with API tests. The response returned has apparently changed, and I would like to know why. self.user.is_superuser = False self.user.save() self.assertEqual(self.user.get_all_permissions(), set()) put_url = reverse(..., kwargs={"pk": 1}) put_data = { ... } response = self.client.put(put_url, json.dumps(put_data), content_type="application/json") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual(response.data, {"detail": "You do not have permission to perform this action."}) This used to pass, but now response.data contains {'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')} and of course the tests fail. The odd thing is that the error code remains 403, not 401. Is there a way to just have the string returned in detail? -
I would like to display only one post at fronted (dajngo framework)
I have posted several posts but am unable to display only one post at the front end from several posts. instead, it displays all the post which is not correct. help appreciated, thank you views.py def ann(request): ann = Announcement.objects.all() context = { 'ann': ann } return render(request, 'Announcement.html', context) index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Community</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <!-- Font Awesome --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css" /> <link rel="stylesheet" href="{% static 'css/bootstrap@5.1.3.css' %}"> <!-- Style.css --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> {% block content %} {% include 'navbar.html' %} {% for ann in ann %} {% if forloop.first %} <div class="col-12 col-lg-10 col-xl-10 col-sm-10" style="margin: auto;"> <div class="row"> <div class="card-body"> <h4 class="card-title" style="text-align: right; border-bottom: 2px solid; color: #46a271; padding: 17px; overflow: hidden; top: 0; z-index: -1000; "> <p style="color: #0e3d42;">Category: {{ann.name}}</p> </h4> <br> <p class="card-text" style="text-align: center;">{{ann.body|safe}}</p> <p> Post created on {{ann.created_date}}</p> </div> </div> </div> {% endif %} {% endfor %} <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> {% include 'footer.html' %} {% endblock %} <!-- Scripts --> <script src="{% static 'jquery/jquery-3.5.1.slim.min.js' %}"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script> <!-- Custom Script --> <!-- <script> function truncateText(selector, maxLength) … -
Django/Python requirements.txt issue with DigitalOcean
I have set up an Ubuntu 18 droplet. When I got to install my django project requirements I hit issues with some of the packages - for example: ERROR: Could not find a version that satisfies the requirement anyjson==0.3.3 (from versions: 0.1, 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.2.5, 0.3, 0.3.1, 0.3.2, 0.3.3) ERROR: No matching distribution found for anyjson==0.3.3 Which is confusing because the version is listed is the "from versions" list. Anyone come across this before? -
Query accessing custom model method - Django ORM
I have 2 models that are relevant to this question: class ParkingOrder(models.Model): # main order that could pay for multiple parkers id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False, primary_key=True) timestamp = models.DateTimeField(null=True, blank=True) status = models.CharField(max_length=15) stripe_charge_id = models.CharField(max_length=150) wallet = models.CharField(max_length=100, null=True, blank=True) # if mobile wallet was used for order (Apple Pay, Google Pay, etc.) def __str__(self): return str(self.id) def walletdisplay(self): return self.wallet.replace('_', ' ').title() class ParkingSession(models.Model): # attributes of a single parker parking_duration = models.ForeignKey(ParkingOption, on_delete=models.PROTECT) parking_order = models.ForeignKey(ParkingOrder, on_delete=models.PROTECT) #refernce which order it belongs to price = models.IntegerField(null=False, blank=False) # store price in pennies license_num = models.CharField(max_length=20, blank=False, null=False) def __str__(self): return str(self.parking_duration) + " - " + str(self.parking_order) + " - " + str(self.license_num) I am trying to query a dictionary of all the wallet types. ParkingSession.objects.filter(parking_order__status='Paid').exclude(parking_order__wallet='No wallet').values('parking_order__wallet').order_by('-parking_order__wallet').annotate(count=Count('parking_order__wallet')) The above query works great but I want the walletdisplay method instead of the wallet attribute. This is because Stripe returns 'apple_pay', 'google_pay' instead of 'Apple Pay', 'Google Pay'. I have tried this, but it throws an error saying that 'walletdisplay' is not an option: ParkingSession.objects.filter(parking_order__status='Paid').exclude(parking_order__wallet='No wallet').values('parking_order__walletdisplay').order_by('-parking_order__walletdisplay').annotate(count=Count('parking_order__walletdisplay')) How can I access the foreign key custom method in the query? -
Get data from specific account_id from Django Manager
I want to have a global manager who return only data from specific account_id This is my globalManager : class GlobalManager(models.Manager): def get_queryset(self): model_name = self.model.__name__ queryset = GlobalQuerySet( model=self.model, using=self._db, hints=self._hints ).filter(is_deleted=False, account_id=account_id) And I call my manager from my model like this : class myClass(models.Model): id = models.AutoField(primary_key=True, editable=False, unique=True) name = models.CharField(max_length=100) objects = GlobalManager() The value of the account_id is available in the header of the request My problem is to provide this account_id to my manager or to my model ! Tech stuff: django==2.2.8 graphene==2.1.8 Thanks -
Time and date stopped updating "python django gunicorn nginx"
Time and date stopped updating after gunicorn restart in a few minutes To not update the time and date again, I also need to restart gunicorn Use nginx on digitalocean for info too for example Now I updated my code and uploaded it to the server I will run the command "sudo systemctl reset gunicorn" To see my update Now you have requested the time and date | looks like this 10:30 at 10:30 that's right But after a few minutes I'm dialing the time and date again It shows 10:31 but it's 10:50 It stops updating completely until I restart "sudo systemctl restart gunicorn" At this time, the time update comes and also some minutes and stops for a while!! -
How to output multiple days as one event using HTMLcalendar
I am using the calendar function using HTMLcalendar module in django. I want to output only one event in a straight line on the calendar when more than 2 days are specified using the 'leave_date' and 'leave_end_date' datefields. Currently, in the code below, an event is added to each of the days corresponding to the period. ex) leave_date: '2021-11-03', leave_end_date: '2021-11-07' #filter events by day I think this part should be corrected, please help! [urls.py] from django.urls import path from . import views app_name = 'leave' urlpatterns = [ path('calendar/', views.CalendarView.as_view(), name='calendar'), # /leave/calendar path('calendar/new/', views.leave, name='leave_new'), # /leave/calendar/new path('calendar/edit/<int:leave_id>/', views.leave, name='leave_edit'), # /leave/calendar/edit/{} path('calendar/delete/<int:leave_id>/', views.leave_delete, name='leave_delete'), # /leave/calendar/delete/{} ] [models.py] from django.db import models from django.urls import reverse class Leave(models.Model): name = models.CharField(max_length=50, blank=True, null=True) leave_date = models.DateField(blank=True, null=True) leave_end_date = models.DateField(blank=True, null=True) take_over = models.TextField(blank=True, null=True) memo = models.TextField(blank=True, null=True) is_deleted = models.BooleanField(default=False) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) @property def get_html_url(self): url = reverse('leave:leave_edit', args=(self.id,)) return f'<a href="{url}"> {self.name} </a> <a data-toggle="modal" data-target="#detail_leave_{self.id}">Detail</a>' [forms.py] from django.forms import ModelForm, DateInput from .models import Leave class LeaveForm(ModelForm): class Meta: model = Leave # datetime-local is a HTML5 input type, format to make date time show on fields widgets = … -
django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'localhost'")
So I am trying to run a django server but I keep getting this error. my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'nlpwords', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 3306, } } I have checked this question but the answer won't work for me: MySQL: django.db.utils.OperationalError: (1698, "Access denied for user 'root'@'localhost'") with correct username and pw These are the lines that they give as an answer: create user 'django'@'localhost' identified by 'django-user-password'; grant usage on *.* to 'django'@'localhost'; grant all privileges on django-database-1.* to 'django'@'localhost'; When I get to the last line I get this error: MariaDB [mysql]> grant all privileges on django-database-1.* to 'django'@'localhost'; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '-database-1.* to 'django'@'localhost'' at line 1 -
Is there a way to turn on/off a particular field from Django admin?
I want to implement a setting in my Django admin dashboard where I can disable/enable a particular field. If I should disable the field, the data in that field will not be rendered on the web page. If I should enable the field, then the data will be shown in the webpage. I only want to do this from my the admin dashboard. This is my models.py: class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(upload_to='products/') description = models.TextField() quantity = models.CharField(max_length=10) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) This is the admin.py: @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'category', 'slug', 'price', 'available') list_filter = ('category', 'available') list_editable = ('price', 'available') prepopulated_fields = {'slug': ('name',)} I want to have the ability to enable/disable (maybe like a toggle button) the description field from my admin dashboard. Is there a way to implement this in my admin.py file? How can I go about this? Thanks. -
problem with django after changing python version
I've been upgrading my Ubuntu server from version 16.04 to 18.04, and upon completion, some of my old sites set up on Django stopped working. In similar threads I found information about trying to create a new virtualenv for each site - unfortunately, in my case this didn't help. I still can't fire up the manage.py file. In response, I get a stack of errors related most likely to importing modules. Traceback (most recent call last): File "/xxx/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/xxx/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "/xxx/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "/xxx/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/xxx/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/xxx/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/xxx/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/xxx/local/lib/python2.7/site-packages/aldryn_forms/contrib/email_notifications/models.py", line 16, in <module> from emailit.api import construct_mail File "/xxx/local/lib/python2.7/site-packages/emailit/api.py", line 2, in <module> import premailer File "/xxx/local/lib/python2.7/site-packages/premailer/__init__.py", line 2, in <module> from .premailer import Premailer, transform File "/xxx/local/lib/python2.7/site-packages/premailer/premailer.py", line 29, in <module> from lxml import etree ImportError: /xxx/local/lib/python2.7/site-packages/lxml/etree.so: undefined symbol: PyFPE_jbuf I created the virtual environment as follows: virtualenv --no-site-packages newvens, pip install -r requirements.txt - copied from previous directory, copying … -
How to return the most recent record in Django using Django Rest Framework?
I want to return the most recent record i.e. with the highest id. I have tried using last() method and order_by approach, but it gives error 'object of type 'Notification' has no len()'. Following is the code: class NotificationViewSet(viewsets.ModelViewSet): queryset = models.Notification.objects.all() permissions_classes = [permissions.AllowAny] serializer_class = serializers.NotificationSerializer -
Integrating ray with django not achieving same performance
I have a Django + Apache + WSGI app which has certain endpoints with specific actions such as: Load/Reload names from database [keeps in memory all the data] Inserting/Updating names [the names loaded in memory] Searching names similarity [search for the names] (would like to improve performance) The action #3 receives some parameters and returns the corresponding matching names according the logig. It tooks around 0.9s to go search around 200k ~ 300k names (multithreading) and I need to improve that response time. I have tried with multiprocessing module but is taking a bit more time than original implementation as I need to do a copy of the data or serialize/deserialize the data everytime. After doing some research I found ray. I have created a dataset and tested it in local and remote mode and the results were 3-5 times faster. Te issue is that I can't find a way of integrate my django app to ray logic and achieve the same performance: ray.init(ignore_reinit_error=True) #collecting some data and then calling to ray results = ray.get(tree.TrieNode.search_name_remote.remote(parameters) The results are almost the same. I only contact the database on the action #1 to load the data so I don't have to use … -
How to check how many anonymous or logged in users are visiting my django app
I have a django app and can't seem to find any straight forward answer to my question. I would like to know how many total users are accessing my site like a counter of users logged in at a time. -
Cannot load Vue JS files from Static folder in Django Template
I have made a templates folder in my app directory. and there I created another folder with my app's name and then I place my html file. index.html. After then I have build another directory name static in my project folder and place all my vue.js files there. index.html : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> </head> <body> <div id="app" class="container"> <h3 class="d-flex justify-content-center"> Vue JS Front End </h3> <h5 class="d-flex justify-content-center"> Dr. Appointment Portal </h5> <nav class="navbar navbar-expand-sm bg-light navbar-dark"> <ul class="navbar-nav"> <li class="nav-item m-1"> <router-link class="btn btn-light btn-outline-primary" to="/home">Home</router-link> </li> <li class="nav-item m-1"> <router-link class="btn btn-light btn-outline-primary" to="/doctor">Doctor</router-link> </li> <li class="nav-item m-1"> <router-link class="btn btn-light btn-outline-primary" to="/appointment">Appointment</router-link> </li> </ul> </nav> <router-view></router-view> </div> <script src="{% static 'variables.js' %}"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js"></script> <script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/qs/6.10.1/qs.min.js"></script> <script src="{% static home.js %}"></script> <script src="{% static doctor.js %}"></script> <script src="{% static appointment.js %}"></script> <script src="{% static app.js %}"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script> </body> </html> In my static folder: In my app.js: const routes=[ {path:'/home',component:home}, {path:'/doctor',component:doctor}, {path:'/appointment',component:appointment} ] const router=new VueRouter({ routes }) const app = new Vue({ router }).$mount('#app') I am getting output (while running Django Server): But, when I … -
Django: save ForeignKey field when form is saved and filter by it
I've two models in my project and I'm having troube with two parts of my code: form.instance.docfile = request.docfile.document here I'd like to autocamatically save the connection between the Color model and the Document one but it doesn't work color = Color.objects.filter(docfile=request.docfile.document).order_by("id")[0] here I'd like to filter and get back only the information about the color for the specific file which the Color model is connnected with and only for the file uploaded from the user. Thank you all for the help. Model class Document(models.Model): ] user = models.ForeignKey(ObjectInformation, on_delete=models.CASCADE) docfile = models.FileField(storage=NumberStorage(), upload_to=directory) upload_date = models.DateField(default=datetime.now) class Color(models.Model): docfile = models.OneToOneField(Document, on_delete=models.CASCADE) color_one = models.CharField(null=True) color_two = models.CharField(null=True) View def upload(request): if request.method == 'POST': form = ColorForm(request.POST, request.FILES) if form.is_valid(): form.instance.docfile = request.docfile.document form.save() if not result.has_errors(): message = 'The form is not valid. ' else: form = ColorForm() documents = Document.objects.filter(user=request.user.userinformation).all() context = { 'documents': documents, 'form': form } return render(request, 'list.html', context) def color_view(request, doc_id): docfile = Document.objects.filter(pk=doc_id) color = Color.objects.filter(docfile=request.docfile.document).order_by("id")[0] context = { 'docfile': docfile, 'color': color } return render(request, 'show.html', context) -
Check content type with if statement to determine what to do
I have django model with a generic relation associated. class SectionLine(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.UUIDField( default=uuid.uuid4, editable=True) content_object = GenericForeignKey('content_type', 'object_id') For the most part that generic relations is associated with one of these two models class Title(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title_name = models.CharField(max_length=40) .... class JobPosition(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... Within a view function I am trying to figure out what model between Title and JobPosition is associated with a specific SectionLine instance so that i can determine what to do next. I now that I can access SectionLine.content_type to see the content type (for example, it prints titles_and_names | title - the app name is titles_and_names) but I don't know what to compare it to... basically, if SectionLine.content_type == ??? -
scrollbar visible on fullscreen mode
I made an image viewer app, that just sends an image to a TV using a raspberry, displaying it on the connected screen via HDMI. The displaying software is Chrome, but I have a tiny problem: There is a very small area of 4px I have to crop the bottom of the image in order to not see a scroll bar. Example: Screen Res is 1024 x 768 using a 1024 x 768 pic in fullscreen mode creates a vertial scollbar decreasing the y pixels by 4 (1024 x 768) makes the scrollbar disappear, but shows me a white border under my image in Chrome for Linux fullscreen mode. I have no fancy css or html code whatsoever: let content = document.getElementById("content"); let ImageDiv = document.createElement("IMG"); ImageDiv.src = pic.file content.appendChild(ImageDiv); with only very little of css: body { margin: 0; } what is the best way to get rid of the border and the scrollbar? -
Geo Django 3.2 django.db.utils.OperationalError: no such function: lwgeom_version
I was trying to fetch the list of Dentists that are nearby from a user's current location. users' current location(latitude and longitude) is sent through query parameters. The dentist's location is saved in a model called location where the id of the dentist is the foreign key and unique identifier. I have used the PointField field from drf_extra_fields.geo_fields in LocationSerializer I'm using python 3.10 and Django 3.2.8 Model class Location(models.Model): id = models.OneToOneField(Dentist, on_delete=models.CASCADE, primary_key=True) location = models.PointField(srid=4326) Serializer from drf_extra_fields.geo_fields import PointField class LocationSerializer(serializers.ModelSerializer): location = PointField() class Meta: model = Location fields = ['id', 'location'] View class NearByDentistView(APIView): def get(self,request): longitude = float(self.request.query_params.get('longitude')) latitude = float(self.request.query_params.get('latitude')) user_location = Point(latitude,longitude,srid=4326) queryset = Location.objects.filter(location__distance_lte=(user_location, D(km=100))) serializer = LocationSerializer(queryset,many=True) return Response(serializer.data) Response Internal Server Error: /api/v1/user/dentist/nearby/ Traceback (most recent call last): File "d:\CODES\Django\SMILE_BACKEND\venv\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "d:\CODES\Django\SMILE_BACKEND\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 421, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such function: lwgeom_version The above exception was the direct cause of the following exception: Traceback (most recent call last): File "d:\CODES\Django\SMILE_BACKEND\venv\lib\site-packages\asgiref\sync.py", line 482, in thread_handler raise exc_info[1] File "d:\CODES\Django\SMILE_BACKEND\venv\lib\site-packages\django\core\handlers\exception.py", line 38, in inner response = await get_response(request) File "d:\CODES\Django\SMILE_BACKEND\venv\lib\site-packages\django\core\handlers\base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "d:\CODES\Django\SMILE_BACKEND\venv\lib\site-packages\asgiref\sync.py", … -
Which view is responsible of rendering `successful installation` page?
I just installed the django and created a new project called api. now in api.api.urls there is the default: from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] so there is url pattern for the admin site, but where is the url pattern for the home page (the page with the rocket) and which view is responsible for rendering it? -
firebase auth not working in django production
The below code works perfectly in localhost but not working in the staging server and there are no errors. it is returning "non_field_error": ["Given token not valid for any token type"] but this same token works perfectly in the localhost. What might be the issue ? cred = credentials.Certificate(BASE_DIR / "cred.json") firebase_admin.initialize_app(cred) class FirebaseAuthentication(BaseAuthentication): def authenticate(self, request): auth_header = request.META.get("HTTP_AUTHORIZATION") token = auth_header.split(" ").pop() decoded_token = auth.verify_id_token(token) uid = decoded_token["uid"] user, created = User.objects.get_or_create(username=uid) return (user, None) -
Deployed prometheus with Django and Kubernetes, how to make it scrape the Django app?
I have a Django project deployed in Kubernetes and I am trying to deploy Prometheus as a monitoring tool. I have successfully done all the steps needed to include django_prometheus in the project and locally I can go go localhost:9090 and play around with querying the metrics. I have also deployed Prometheus to my Kubernetes cluster and upon running a kubectl port-forward ... on the Prometheus pod I can see some metrics of my Kubernetes resources. Where I am a bit confused is how to make the deployed Django app metrics available on the Prometheus dashboard just like the others. I deployed my app in default namespace and prometheus in a monitoring dedicated namespace. I am wondering what am I missing here. Do I need to expose the ports on the service and deployment from 8000 to 8005 according to the number of workers or something like that? My Django app runs with gunicorn using supervisord like so: [program:gunicorn] command=gunicorn --reload --timeout 200000 --workers=5 --limit-request-line 0 --limit-request-fields 32768 --limit-request-field_size 0 --chdir /code/ my_app.wsgi my_app service: apiVersion: v1 kind: Service metadata: name: my_app namespace: default spec: ports: - name: http port: 80 protocol: TCP targetPort: 80 selector: app: my-app sessionAffinity: None … -
Django: POST and GET request and rendering on a template
I'm probably lost in a glass of water but at the moment I can't figure it out. I'm working on a restaurant capstone project where the client is able to see a menu page, a purchase page and the owner of the restaurant after login is able to manage and enter a new recipe and create his personal menu. What I'm trying to do is: when the owner of the restaurant submits a POST request where he entered the recipe, i want that the recipe appear also in the page where is the menu. In this way is able to update new recipe and change maybe the old one. (I copy model, form and view code for a complete overview): form.py class RecipeForm(forms.ModelForm): class Meta: model = Recipe fields = '__all__' model.py class Recipe(models.Model): name = models.CharField(max_length=50) ingredients = models.CharField(max_length=500) def __str__(self): return self.name View.py def recipeEntry(request): recipe_menu = Recipe.objects.all() form = RecipeForm() if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): form.save() return redirect("recipe") context = {'form':form, 'recipe_menu':recipe_menu} return render(request, 'inventory/recipe.html', context) recipe.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Recipe</title> </head> <body> <form method="post", action="">{% csrf_token %} {{form.as_p}} <input type="submit" value="Add Recipe"> </form> {% for rec in recipe_menu … -
How do I send Django object as parameter in Javascript?
So as mention in title, I'm trying to send my Django object to JavaScript so I can massage it in the front end. Let me show you the code (simplified). views.py def main_page(request): contents = Contents.objects.all() context = { 'contents' : contents } return render(request, 'main/home.html', context) template {% for u in all_ans_us_paginated %} <div class="row"> <div class="col"> <div class="" id="{{u.id}}" onclick="DetailModal('{{u}}')"> </div> </div> </div> {% endfor %} ... <script> function DetailModal(u) { console.log('{{u.author}}'); console.log('{{u.body}}'); } </script> My intention is to show a modal when the click event is triggered. But putting the modal part aside, I can't pass data as parameter to JavaScript. *I don't want to make any changes in the python code. Is it possible to do it only with HTML and JavaScript? **JSON.parse(u) won't work, because u is string.