Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
New Relic python agent + gunicorn + gevent crashing
I am switching my application over to use gevent instead of threads with gunicorn. I have also been using New Relic to monitor my application successfully. However, when I using the combination of both of them, my application becomes really laggy ans also crashes. In the moment, I remove gevent or New Relic, everyhing works fine. This would be my goal to work: web: newrelic-admin run-program gunicorn config.wsgi_gevent:application -c config/gunicorn_gevent.config.py --worker-class gevent --worker-connections 100 --max-requests=100 --max-requests-jitter=50 --bind 0.0.0.0:8000 As said, that one does not work. These ones do: New relic + threads web: newrelic-admin run-program gunicorn config.wsgi:application --bind 0.0.0.0:8000 Gunicorn with gevent web: gunicorn config.wsgi_gevent:application -c config/gunicorn_gevent.config.py --worker-class gevent --worker-connections 100 --max-requests=100 --max-requests-jitter=50 --bind 0.0.0.0:8000 Logs before the browser is just loading and nothing happens anymore: 12:05:53 AM web.1 | [2023-04-19 00:05:53 +0300] [14496] [INFO] Starting gunicorn 20.1.0 12:05:53 AM web.1 | [2023-04-19 00:05:53 +0300] [14496] [INFO] Listening at: http://0.0.0.0:8000 (14496) 12:05:53 AM web.1 | [2023-04-19 00:05:53 +0300] [14496] [INFO] Using worker: gevent 12:05:53 AM web.1 | [2023-04-19 00:05:53 +0300] [14499] [INFO] Booting worker with pid: 14499 12:06:07 AM web.1 | [2023-04-18 21:06:07 +0000] [14499] [INFO] Autorestarting worker after current request. 12:06:08 AM web.1 | [2023-04-18 21:06:08 +0000] [14499] [INFO] … -
Issue with finding a rival in a Django web page
I am working on a Django web application that allows users to register teams, add players to those teams, and then find a rival team. However, I am experiencing an issue when users click the "Find Rival" button, as the system does not seem to find an appropriate rival team and leaves the user waiting. Here's an overview of the web page structure: The homepage (index.html) allows users to register a team by entering their details and location. In the create_players.html page, users can register players for the previously created team. After registering the players, users can click the "Find Rival" button to find a rival team. The issue seems to be related to the following code: The JavaScript function findRival() in the create_players.html template is responsible for finding a rival. When the "Find Rival" button is clicked, this function sends a POST request to the /find_rival/ route on the Django server. Potential causes of the issue include the findRival() function not sending the team data to the Django server correctly, the find_rival view on the Django server not properly processing the received data and/or not returning the rival information in the expected format, and the JavaScript code in the … -
Having trouble with View Function in Django, how can I fix it?
The Save function and the Search function are not working for some reason. I keep getting redirected to the error.html template in the converter function. Here's views.py: from django.shortcuts import render from . import util from markdown2 import Markdown import random def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def New(request): return render(request, "encyclopedia/new.html") def save(request): if request.method == 'POST': title = request.POST.get('title','') content = request.POST.get('content', '') entry = util.list_entries() if title in entry: return render(request, "encyclopedia/exists.html") else: util.save_entry(title, content) return converter(request, title) def Random1(request): entry = util.list_entries() rand_entry = random.choice(entry) return converter(request, rand_entry) def converter(request, title): entry = util.list_entries() markdowner = Markdown() if title in entry: content = util.get_entry(title) data = markdowner.convert(content) return render(request, "encyclopedia/entry.html", { "data": data }) else: return render(request, "encyclopedia/error.html") def search(request): if request.method == 'POST': input = request.POST.get('q', '') html = converter(request,input) entries = util.list_entries() if input in entries: return render(request, "encyclopedia/entry.html", { "data": html, }) else: search_pages = [] for entry in entries: if input in entry: search_pages.append(entry) return render(request, "encyclopedia/search.html", { "entries": search_pages, }) I want the save function to be able to save a new entry made by the user and search function to be able to search for any entry … -
Zappa deployment "cannot import name 'discovery_cache' from 'googleapiclient'
I have a zappa/django AWS deployment that is mostly working, but it fails with this stack trace: File "/var/task/help_desk/models.py", line 409, in send_emails service = gmail.get_service(sender_id="coach" if self.thread.cat==Thread.CAT_COACH else None) File "/var/task/help_desk/gmail.py", line 22, in get_service service = build('gmail', 'v1', credentials=delegated_credentials) File "/var/task/googleapiclient/_helpers.py", line 130, in positional_wrapper return wrapped(*args, **kwargs) File "/var/task/googleapiclient/discovery.py", line 287, in build content = _retrieve_discovery_doc( File "/var/task/googleapiclient/discovery.py", line 387, in _retrieve_discovery_doc from . import discovery_cache ImportError: cannot import name 'discovery_cache' from 'googleapiclient' (/var/task/googleapiclient/__init__.py) This does not fail when running it on a local copy. I have hunted around, and this module is installed in the google-api-python-client package. This package is listed in my requirements.txt and is present in my local virtual env. I am not sure why it is not present in the zappa deployment or how to get it there. If I list the lib/googleapiclient/discovery_cache, it is present on my local project and it is also present if I run the 'pip show -f google-api-python-client' command locally. -
TypeError at /signin/ 'module' object is not callable
As I'm working on django for the first time, so I was trying to create a user authentication page. Everything works fine but when I try to signin Im getting an error. app name : authentication views.py from django.shortcuts import redirect, render from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import login, logout import authentication def home(request): return render(request, "authentication/index.html") def signup(request): if request.method == "POST": username = request.POST['username'] fname = request.POST.get('fname') lname = request.POST.get('lname') email = request.POST['email'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] myuser = User.objects.create_user(username,email,pass1) myuser.first_name = fname or '' myuser.last_name = lname or '' myuser.save() messages.success(request, "Your account has been successfully created.") return redirect('signin') return render(request, "authentication/signup.html") def signin(request): if request.method == "POST": username = request.POST['username'] pass1 = request.POST['pass1'] user = authentication (request,username=username,password=pass1) if user is not None: login(request,user) fname = user.first_name return render(request,"authentication/index.html", {'fname':fname}) else: messages.error(request,"Bad credentials!") return redirect('home') return render(request, "authentication/signin.html") def signout(request): logout(request) messages.success(request, "logged out successfully!") return redirect('home') urls.py from django.urls import path from . import views urlpatterns = [ path('signup/', views.signup, name='signup'), path('signin/', views.signin, name='signin'), path('signout/', views.signout, name='signout'), ] templates/signin.html <!DOCTYPE html> <html> <body> <h3>SignIn</h3> {% for message in messages %} <div class="alert alert-{{ message.tags }} … -
Return fake dates for every blog post - bypass django's auto now
I am testing whether my blog posts are in reverse chronological order. To do so, I must set random dates for each post created. I'm using faker to set the dates. I am getting back a fake date, but it's the same date for every post. Is auto now still the issue here, or am I not using Faker correctly? Factory: fake = Faker() mocked = fake.date_time() class BlogPageFactory(wagtail_factories.PageFactory): class Meta: model = models.BlogPage with patch('django.utils.timezone.now', mocked): date = mocked # date = datetime.date.today() author = factory.SubFactory(UserFactory) slug = factory.sequence(lambda n: f"post{n}") snippet = factory.sequence(lambda n: f"Article {n} snippet...") body = "Test post..." featured_image = factory.SubFactory(wagtail_factories.ImageFactory) featured_article = False Models: class BlogPage(Page): date = models.DateField("Post date") snippet = models.CharField( max_length=250, help_text="Excerpt used in article list preview card." ) body = RichTextField(blank=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) featured_image = models.ForeignKey("wagtailimages.Image", on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) featured_article = models.BooleanField(default=False) content_panels = Page.content_panels + [ MultiFieldPanel( [ FieldPanel("date"), FieldPanel("tags"), ], heading="Blog Information", ), FieldPanel("snippet"), FieldPanel("featured_image"), FieldPanel("body"), FieldPanel("author"), InlinePanel("page_comments", label="Comments"), ] search_fields = Page.search_fields + [index.SearchField("body")] parent_page_types = ["CategoryIndexPage"] subpage_types = [] def serve(self, request, *args, **kwargs): """ Method override to handle POST conditions for blog comments, ``BlogComment``. """ from .forms import CommentForm if request.method … -
Django cookies not being saved in Safari nor Firefox
I recently started to test cookies in my development environment as I need it for token storage and csrf token. I came accross the issue of firefox and safari not setting the cookies in their storage tabs. If safari's 'prevent cross-site tracking' is off the behavior is the same with Firefox. However, not all users if any will have this setting off. With the previous mentioned, both browsers do not save the cookies in the storage tab. But, the cookies are received as when I click in an api testing button I have after loggin in, it works and the resources are accessed since cookies are sent. But, neither Safari nor Firefox show it in the cookies tab. Here is the response after log in. Response HTTP/1.1 200 OK Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: https://localhost:3000 Access-Control-Expose-Headers: Content-Type, X-CSRFToken Allow: POST, OPTIONS Connection: close Content-Length: 714 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Tue, 18 Apr 2023 17:11:05 GMT Referrer-Policy: same-origin Server: Werkzeug/2.2.3 Python/3.9.6 Set-Cookie: auth1=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9; expires=Tue, 18 Apr 2023 17:21:05 GMT; HttpOnly; Max-Age=600; Path=/; SameSite=None; Secure Set-Cookie: csrftoken=Y1GzI80DfRc3lMkUnboTYeA3AZBY4aih; expires=Tue, 16 Apr 2024 17:11:05 GMT; Max-Age=31449600; Path=/; Secure Vary: Accept, Cookie, Origin X-Content-Type-Options: nosniff X-Frame-Options: DENY I am using Django and React both on localhost, … -
my elastic beanstalk application doesn't reflect the latest commit in the live environment
I am deploying my Django app via the eb CLI. I commit my changes to git and deploy (with eb deploy). In the past I would see my changes reflected after a deploy, now I do not. It is as if the application version is being cached on EB's side.Thanks in advance for any help. I checked the source on S3 and it is the latest version, so I have no idea why the live site (also accessed via eb open after deployment to be sure) doesn't reflect. I added some simple console logging to be certain, and it is missing. I've tried restarting the server and rebuilding the environment. Nothing has worked. I also deleted all previous application versions, so the only remaining one has the changes I want, then redeployed and restarted. Still not the version I want running on the environment. -
A form with fields that are associated with different database tables does not pass validation and does not create the necessary record in the db
I need to create an object in a database table using the form. This table is linked to other tables by means of a One-to-Many relationship. that is, through the ForeignKey. The fields are filled in by means of a drop-down list, which displays the objects that are in the tables associated with these fields. When I try to send data from the form, it does not pass validation and does not send anything. forms.py: class receiptForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['is_apartment'].empty_label = "Не выбрано" self.fields['is_owner'].empty_label = "Не выбрано" self.fields['is_receipt_type'].empty_label = "Не выбрано" class Meta: model = receipt fields = ['is_apartment', 'is_owner', 'is_receipt_type', 'date', 'receipt_file'] views.py: def create(request): error = '' if request.method == "POST": form = receiptForm(request.POST) if form.is_valid(): form.save() return redirect('main') else: error = "Форма была неверной" form = receiptForm() data = { 'form': form, 'error': error } if (request.GET.get('error')): return render(request, "main/main.html", context={'error': request.GET.get('error')}) return render(request, "main/main.html", data) models.py: class apartment(models.Model): address = models.TextField("Адрес квартиры", max_length=500, default="") def __str__(self): return self.address class owner(models.Model): surname = models.CharField("Фамилия", max_length=50, default="") name = models.CharField("Имя", max_length=50, default="") middle_name = models.CharField("Отчество", max_length=50, default="") email = models.EmailField("Email", max_length=254) def __str__(self): return f'{self.surname} {self.name} {self.middle_name}' class receipt_type(models.Model): pattern = models.FileField("Шаблон", upload_to='pattern') title … -
Testing a Consumer is failing when use database_sync_to_async Djagno Channels
So, I didn't use channels for a very long time, so let's be that this is a first time that I have tried to do something. I am trying to create 1 Consumer, wrapped with 1 custom Auth middleware and I want to test my Consumer, if it behaves properly in various test cases. Django==4.1.7 channels==4.0.0 middleware.py @database_sync_to_async def get_user(email): user = User.objects.get(email=email) if not user.is_active: raise AuthenticationFailed("User is inactive", code="user_inactive") return user class OktaASGIMiddleware(BaseMiddleware): def __init__(self, inner): super().__init__(inner) self.okta_auth = OKTAAuthentication() async def __call__(self, scope, receive, send): try: # token checking and retrieval claims = self.okta_auth.jwt_verifier.parse_token(token)[1] user = await get_user(claims["email"]) scope["user"] = user except Exception as exc: await send({"type": "websocket.close"}) raise return await self.inner(scope, receive, send) tests.py @aioresponses() async def test_connect_with_correct_token_edit_resource_draft( self, mocked_io_request ): mocked_io_request.get( # mocked request/respones ) communicator = WebsocketCommunicator( application, f"/ws/draft/1/?token={sometoken}" ) connected, subprotocol = await communicator.connect() self.assertTrue(connected) So, the issue is, when I use database_sync_to_async as Docs suggests, I am getting: django.db.utils.InterfaceError: connection already closed. When I use from asgiref.sync import sync_to_async, everything works fine and I can test my consumer properly. Also, i an attempt to avoid database_sync_to_async, I switched from JsonWebsocketConsumer to AsyncJsonWebsocketConsumer, but still no help. NOTE: Both of this code works … -
How can i manage leveldb database to cope with Django framework
i am trying to develop a web application that uses leveldb as a database, knowing that leveldb doesn't support an SGBD,how can i deal with it in order to manage data on django framework I suggest to use a relational data base to manage users,sessions and other standard data, and try to use leveldb just for that purpose that i am using for. -
Incrementing an IntegerField in Django
I'm trying to implement the Polls app like the one in the Django documentation. I have an IntegerField to represent the number of votes an option has in my Polls app but if I try to add the voter to the list of voters and increment it by one in my views.py ever time a user votes, it adds to the user to the list of voters but the vote count doesn't increase. This is my Choice model... votes = models.IntegerField(default=0) voters = models.ManyToManyField(UserProfile, blank=True, related_name="my_votes") This is my vote function in views.py option.votes += 1 user = UserProfile.objects.get(user = request.user) option.voters.add(user) How do i fix this please? -
Django: while updating record: ValueError: Cannot force an update in save() with no primary key
There are similar issues on SO, but none alike this. I would like to update a field in a record of a m2m model which has a unique constraint on attendee + training. This model is defined as (model.py): class Occurrence(models.Model): attendee = models.ForeignKey(Attendee, on_delete=models.CASCADE) training = models.ForeignKey(Training, on_delete=models.CASCADE) attended_date = models.DateField(default=date(1900, 12, 31)) class Meta: constraints = [ models.UniqueConstraint(fields=['attendee', 'training'], name='unique_attendee_training') ] Now, consider e.g. that John has taken the Python course and already exists as record in the db. If I try get the date of when the training occurred, I would go like this: from trainings.models import Attendee, Training, Occurrence from datetime import date, datetime attendee = Attendee.objects.get(pk='john@gmail.com') training = Training.objects.get(pk='python310') occurrence = Occurrence.objects.get(attendee=attendee, training=training) print(occurrence.attended_date) # datetime.date(2021, 11, 4) However, if I try to update the date of this record, I get the error. occurrence = Occurrence(attendee=attendee, training=training, attended_date=date(2021, 11, 5)) occurrence.save(update_fields=["attendee", "training", "attended_date"]) The error being: ValueError: Cannot force an update in save() with no primary key. How do I update this record? Note I believe this should be enough to understand the question. But if you want to reproduce the whole issue, I post here the models (model.py) for Attendees and Trainings. class Attendee(models.Model): … -
Python: cannot pickle '_io.BufferedRandom' object [Django] [Cacheops]
I am setting up django cacheops and I am running into an issue regarding pickling my data. My Models have this kind of structure: class A(models.Model): # ... class B(models.Model): link_1 = models.ForeignkeyField(A) link_2 = models.ForeignkeyField(A) link_3 = models.ForeignkeyField(A) def get_link(self): # function does some checks here, decides if link_1, link_2 or link_3 should be loaded link_to_load = "link_1" # fixed for simplicity return getattr(self, link_to_load, None) When I use cacheops, I get this error: cannot pickle '_io.BufferedRandom' object. It also occurs when I use A.object.get(pk=some_pk) instead of getattr. Has someone a tip, how change my code that it does not happen? -
Filter a Query Set by Reverse Foreign Key
If I have the following: class Asset(models.Model): name = models.TextField(max_length=150) project = models.ForeignKey('Project') class Project(models.Model): name = models.TextField(max_length=150) What argument do I pass to Project.objects.filter() to get all Projects that have no associated Assets. -
django runserver in http
I'm a little new to django so bear with me. I have an app that's running just fine in HTTPS. In settings.py I have this bit of line that enables it: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Out of curiosity, instead of disabling this every time to test pages and applications, is there a way to enable http for only 127.0.1:8000 and not *.example.com? Or is this a bad practice to even attempt? -
I am getting same problem while generating test api key
Please help to resolve this error I opened Paytm dashboard and visited to test api details but it shows nothing. I want test api merchant Id and key. Please help -
Ordering a QuerySet by the first object in a prefetch_related query
If I have the following models, describing Books which can have several different Titles: class Book(models.Model): publisher = models.CharField(max_length=255) class BookTitle(models.Model): work = models.ForeignKey(Book, related_name="titles", on_delete=models.CASCADE) title = models.CharField(max_length=255) I'm fetching a QuerySet of Books, pre-fetching their BookTitles, like this: from django.db.models import Prefetch books = Book.objects.prefetch_related( Prefetch( "titles", queryset=BookTitle.objects.all() ) ) I'd like to be able to order the QuerySet by the first of the BookTitles. How would I do that? (This is a very simplified example of my actual code to explain the basic question.) -
Django IntegrityError at admin, null value of id violates the not-null constraint
I am fairly new to Django and I use Django 4.2 and PostgreSQL's latest version. I have this issue with my code, I have created models for a blog post. In the admin, I am trying to test it out to see if everything is working the way I expect it to, but I have reached an error. I am trying to add tags to the blog post. That is like tags that describe what kind of genre the blog post is. This is what my models.py file looks like: class BlogPost(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) id = models.UUIDField(unique=True, primary_key='True', editable=False) post_title = models.CharField(max_length=300, blank=True, null=True, verbose_name='Title of blog post') post_image = models.ImageField(upload_to='posts/%Y/%m/%d', default='static/images/avatar.jpg', blank=True, null=True, verbose_name='Blog post picture') tags = models.ManyToManyField('Tags', blank=True, verbose_name='Tags seperated by #') post_body = models.TextField(blank=True, null=True, verbose_name='body of user') votes_total = models.IntegerField(default=0, blank=True, null=True) created_time = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return self.post_title class Tags(models.Model): id = models.UUIDField(editable=False, unique=True, primary_key=True) tag = models.CharField(max_length=200) def __str__(self) -> str: return self.tag class Comments(models.Model): blogpost = models.ForeignKey(BlogPost, on_delete=models.CASCADE, blank=True, null=True) comment_body = models.TextField(blank=True, null=True) VOTE_TYPE = ( ('up', 'UP VOTE'), ('down', 'DOWN VOTE'), ) value = models.CharField(max_length=200, choices=VOTE_TYPE) id = models.UUIDField(editable=False, unique=True, primary_key=True) def __str__(self) -> … -
getting model object returned matching query does not exist
I want to display what user is posted from a Book model when others user visited his public_profile page, to do that, i had to use this method: def public_profile(request, slug): profile = get_object_or_404(Profile, slug=slug) book = Book.objects.get(slug=slug) context = { 'profile': profile, 'book': book } return render(request, 'public_profile.html', context) But using that method returned: Book matching query does not exist. in the public_profile template. my url to public_profile page: <p class="title is-4"><a href="{{ book.get_user_public_url }}"> {{ book.user }} </a></p> my model class Book(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) audio = models.FileField(upload_to='audio') title = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to='audio-image') introduction = models.TextField(max_length=500) slug = models.SlugField(unique=True) def get_user_public_url(self): return reverse('Public-Profile', kwargs={'slug': self.user.profile.slug}) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) profile_photo = models.ImageField(upload_to='profile-image', default='static/dafault.jpg') twitter = models.URLField(blank=True, null=True, unique=True) website = models.URLField(blank=True, null=True, unique=True) linkedln = models.URLField(blank=True, null=True, unique=True) country = models.CharField(max_length=70, blank=True, null=True,) about = models.TextField(max_length=700, blank=True, null=True) slug = models.SlugField(max_length=100, unique=True) -
How to handle errors correctly in django?
I have a question, I know that it is possible to do global exception handling in python, but how to do it for all views, namely, I am interested in DetailView, but others will also come in handy.I understand that you need to give your own examples of solutions, but could you give an example of how this can be done, because I have no ideas at all how to do it. I want to do global error handling so that it can be done like this try: current_profile = Profile.objects.get(user_connected_id=current_user_object) except ObjectDoesNotExist SomeERROR....: logger.info('Object user_connected_id not found....') raise ObjectDoesNotExist And if I don't handle the error that appears, then I want it to work in the global handler. And if it's not difficult: what should I do correctly with errors in this handler, other than logging? I need the DetailView handler most of all -
AttributeError: 'NumberObject' object has no attribute 'indirect_reference'
I've been trying to create multiple pdfs and merge them using pypdf (Version 3.7.1). The static data such as images and fonts render out perfectly within the html but don't in pdfs. Following is my code and the error I'm encountering query_set = booklet.objects.filter(booklet_id = id) combine = [] for i in query_set: size = i.size options = { 'page-size': f'{size}', 'orientation': 'Landscape' if i.template_mode == "2" else "Portrait", 'margin-top': '0mm', 'margin-right': '0mm', 'margin-bottom': '0mm', 'margin-left': '0mm', 'encoding': "UTF-8", 'dpi': 900 } url = f"http://ipaddress/test?ids={get_ids}&uuid={i.uuid}&size={i.size}&mode={i.mode}&type_set={i.te_type}&template={i.name}&pre{id.id}" pdfkit.from_url(url, output_path=f"{file_path}/pdfs/{i.te_type}_{i.name}_{i.id}_.pdf", options=options, verbose=False) combine.append(f"{file_path}/pdfs/{i.te_type}_{i.name}_{i.id}_.pdf") merger = PdfWriter() for pdfs in combine: merger.append(pdfs) pdf_name = "base.pdf" merger.write(pdf_name) merger.close() return JsonResponse({"pdf" : pdf_name"}) I have tried cnfiguring the nginx file, thinking it could be the case but it is not I have tried modifying my code and relocating static folder to no success. I have tried rendering static images into a separate template but as i mentioned above they render in just fine but not in the pdf generated by pypdf -
Pycharm professional syntax highlighting for JS contained in a block inside a script tag
While writing JS for a Django application using the Django templating language, I am getting a weird formatting problem as below: Defining a domready block in the base.html file: <script> const csrftoken = Cookies.get('csrftoken'); document.addEventListener('DOMContentLoaded', (event) => { //DOM loaded {% block domready %} {% endblock %} }) </script> Using the block in another template file list.html: {% extends "base.html" %} {% block domready %} var page = 1; var emptyPage = false; var blockRequest = false; window.addEventListener('scroll', function (e) { var margin = document.body.clientHeight - window.innerHeight - 200; if (window.pageYOffset > margin && !emptyPage && !blockRequest) { blockRequest = true; page += 1; fetch('?images_only=1&page=' + page).then(response => response.text()).then(html => { if (html === "") { emptyPage = true; } else { var imageList = document.getElementById('image-list'); imageList.insertAdjacentHTML('beforeend', html); blockRequest = false; } }) } }); // start a synthetic scroll event on page load so that the next page loads in case the browser window is big enough const scrollEvent = new Event('scroll'); window.dispatchEvent(scrollEvent); {% endblock %} Pycharm's formatting for JS code is not working in the list.html file. Is there any way to force Pycharm Professional to highlight the syntax and format the JS code in the domready block … -
Invalid JSON error reported whenever a PointField is saved with the GooglePointFieldWidget in the Django admin
I am using Django 4.1 and GooglePointFieldWidget (from django-map-widgets) on PointFields (from django-geojson). The widget gets displayed as it should and I'm able to change the coordinates, set a marker on the map or even type in an address. All good. The problem is that I'm getting a validation error upon saving the object because GooglePointFieldWidget fills in the hidden textarea of the field with invalid JSON, something like POINT (26.2616671966018 65.06716787213769) when Django expects something like {'type': 'Point', 'coordinates': [26.2616671966018, 65.06716787213769]} How can I solve this validation error? -
Wagtail 500 server error with DEBUG=False
I deployed the Wagtail site on Ubuntu 22.04 following digitalocean's instructions (Nginx + Gunicorn). The site works without errors when DEBUG=True, but when I put False I get Server Error (500) when going to any page. At the same time admin panel works without errors, path to static files is correct. Error.log nginx are clean. What can be the problem? I have already tried everything. gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=user1 Group=www-data WorkingDirectory=/home/user1/projectdir ExecStart=/home/user1/projectdir/env/bin/gunicorn \ --access-logfile - \ --workers 5 \ --bind unix:/run/gunicorn.sock \ --env DJANGO_SETTINGS_MODULE=projectname.settings.production \ projectname.wsgi:application [Install] WantedBy=multi-user.target nginx config: server { listen 80; server_name mysite.com www.mysite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/user1/projectdir/static/; } location /media/ { alias /home/user1/projectdir/media/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } }