Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dockerized react app cant communicate with dockerized django app
I have created a django app running at https://localhost:8000 using sslserver with self-signed certificates. My react app running at https://localhost:8000 also with self-signed certificates. When i run those two in a terminal both of them running perfectly and they communicate with each other. My problem is that when i try to run those two from docker desktop when i make a call from the frontend to the backend returns: 2024-01-12 21:43:00 Proxy error: Could not proxy request /main.dd206638be0188052640.hot-update.json from localhost:3000 to https://localhost:8000/. I should mention that when i make a call to the backend with Postman it runs normaly. Django settings.py: ALLOWED_HOSTS = [ 'localhost' # Provide the host that the server allows. ] # Config for CORS-Headers. CORS_ALLOWED_ORIGINS = [ # Provide frontend address. "https://localhost:3000" ] React package.json: "proxy": "https://localhost:8000", docker-compose.yml version: '3.10' services: django-backend: container_name: proxmox-project-backend build: context: ./django-backend dockerfile: Dockerfile image: django-backend:0.0.1 ports: - '8000:8000' react-frontend: container_name: proxmox-project-frontend build: context: ./react-frontend dockerfile: Dockerfile image: react-frontend:0.0.1 ports: - '3000:3000' stdin_open: true tty: true environment: - HTTPS=true - SSL_CRT_FILE=/app/ssl/react.crt - SSL_KEY_FILE=/app/ssl/react.key -
Overriding delete method in django model
I have a Page model that during the saving of objects calls the print within the save method. However, when objects are being deleted, no prints are triggered, and it seems like the delete method is never being called. How should I override the default delete method then? class Page(models.Model): image = models.ImageField() number = models.PositiveIntegerField(default=0, blank=True, null=True) chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE) def get_upload_path(self, filename): work_slug = self.chapter.volume.work.slug translator_name = slugify(self.chapter.volume.translator) volume_number = self.chapter.volume.number chapter_number = self.chapter.number name, extension = filename.rsplit('.', 1) return f'media/{work_slug}/{translator_name}/volumes/volume-{volume_number}/chapters/chapter-{chapter_number}/page-{self.number}.{extension}' def save(self, *args, **kwargs): if not self.pk: last_page = self.chapter.page_set.last() if last_page: self.number = last_page.number + 1 self.image.name = self.get_upload_path(self.image.name) self.image.storage = s3 print(f"Saving Page with image: {self.image.name}") super().save(*args, **kwargs) def delete(self, *args, **kwargs): print(f"Deleting Page with image: {self.image.name}") image_name = self.image.name try: s3.delete(image_name) print(f"Successfully deleted from S3: {image_name}") except Exception as e: print(f"Error deleting from S3: {e}") super().delete(*args, **kwargs) -
How to use Django's ORM to update the value for multiple keys in a JsonField using .update() method?
I have a model field I am trying to update using Django's .update() method. This field is a JsonField. I am typically saving a dictionary in this field. e.g. {"test": "yes", "prod": "no"} Here is the model: class Question(models.Model): # {"test": "yes", "prod": "no"} extra_data = models.JSONField(default=dict, null=True, blank=True) I am able to update a key inside the dictionary using this query (which works fine by the way): Question.filter(id="123").update(meta_data=Func( F("extra_data"), Value(["test"]), Value("no", JSONField()), function="jsonb_set", )) The question now is, is there a way I can update the multiple keys at once(in my own case, two) using the .update() as shown in the above query? I want to use the .update() method instead of .save() to achieve this so I can avoid calling a post_save function. -
getting the media url right in django and nginx (I must be doing it wrong in nginx)
I am stuck with a server 500 server error at a form only when it is about to save the pictures (the rest of the forms belonging to other models are saved in the db ok) I didn't have the problem in development, but I think I know why I am not coming on, because there is an extra configuration for media URL, and that is nginx Could anyone tell me how to to this well? I have in my production server pulled the github app at: /home/boards/myapp In the settings.py: MEDIA_ROOT = BASE_DIR /'media' MEDIA_URL = "/media/" In urls.py ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In Nginx (Here is where I must be screwing up because I don't nginx in development and it works well) location /media/ { alias /home/boards/media/; } Well, this is the model but like I said, it works great in development class Photos(models.Model): def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user, filename) images = ResizedImageField(size=[500, 300], upload_to=user_directory_path, blank=True, null=True) I am running gunicorn, nginx and supervisor. If I make changes to nginx, do I have to reload, restart etc or does supervisor take care of that? -
Pydantic: pass the entire dataset to a nested field
I am using django, django-ninja framework to replace some of my apis ( written in drf, as it is becoming more like a boilerplate codebase ). Now while transforming some legacy api, I need to follow the old structure, so the client side doesn't face any issue. This is just the backstory. I have two separate models. class Author(models.Model): username = models.CharField(...) email = models.CharField(...) ... # Other fields class Blog(models.Model): title = models.CharField(...) text = models.CharField(...) tags = models.CharField(...) author = models.ForeignKey(...) ... # Other fields The structure written in django rest framework serializer class BlogBaseSerializer(serializers.Serializer): class Meta: model = Blog exclude = ["author"] class AuthorSerializer(serializers.Serializer): class Meta: model = Author fields = "__all__" class BlogSerializer(serializers.Serializer): blog = BlogBaseSerializer(source="*") author = AuthorSerializer() In viewset the following queryset will be passed class BlogViewSet(viewsets.GenericViewSet, ListViewMixin): queryset = Blog.objects.all() serializer_class = BlogSerializer ... # Other config So, as I am switching to django-ninja which uses pydantic for schema generation. I have the following code for pydantic schema AuthorSchema = create_schema(Author, exclude=["updated", "date_joined"]) class BlogBaseSchema(ModelSchema): class Meta: model = Blog exclude = ["author", ] class BlogSchema(Schema): blog: BlogBaseSchema author: AuthorSchema But as you can see, drf serializer has a parameter called source, where … -
Django paginate table without get the entire table
there is some way to paginate a django model table without get all the db? Something like Db => 100 records => [id:0...,id:1...,id:n] Query => ...?page=1 Return => [id:0...,id:1...,id:25] Query => ...?page=2 Return => [id:26...,id:27...,id:50] -
Daphne Docker Django ModuleNotFoundError: No module named 'yourproject'
When I try to run daphne in docker I have this problem. I have no idea to fix it :) I use docker compose to build it. my project -nginx -redis -daphne -django channels ~/pyprj/Django# docker logs 3517329befc9 New pypi version: 0.2.0.2 (current: 0.1.8.7) | pip install -U g4f Traceback (most recent call last): File "/usr/local/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/usr/local/lib/python3.12/site-packages/daphne/cli.py", line 233, in run application = import_by_path(args.application) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 994, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/Django/gptweb/gptweb/asgi.py", line 16, in <module> django_asgi_app = get_asgi_application() ^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/core/asgi.py", line 12, in get_asgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.12/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/conf/__init__.py", line 89, in __getattr__ self._setup(name) File "/usr/local/lib/python3.12/site-packages/django/conf/__init__.py", line 76, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/conf/__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/importlib/__init__.py", line 90, in … -
Scheduling tasks with Django
I have a site I'm working on that I'd like to add an option to sign up for a weekly newsletter type thing. I did a lot of looking around, and I was wondering if the python schedule library is an okay thing to use for this (https://schedule.readthedocs.io/en/stable/). Could I have my website running and then a scheduler running in tandem that runs a django management command to send emails to those who sign up? I'm fairly new to this kind of thing, so I just wanted to check since I couldn't really find any info of other people doing this. I have a script that sends emails and when I use the scheduler to send them every however many minutes it works, but I'm just wondering about the scalability of this. I think I'd like to avoid using something like celery since it seems like sort of a big solution to a small problem. -
Issue with Editing Custom User Models in Wagtail Projec
I have a custom user model in my Wagtail project. I created this custom model following the guidelines in the Wagtail documentation (https://docs.wagtail.org/en/stable/advanced_topics/customisation/custom_user_models.html#custom-user-forms-example). However, in the administrative part, when editing a user, I am unable to make edits to a user, and only a button to add a new user appears. models.py class User(AbstractUser): """ Default custom user model for SciELO Content Manager . If adding fields that need to be filled at user signup, check forms.SignupForm and forms.SocialSignupForms accordingly. """ #: First and last name do not cover name patterns around the globe name = models.CharField(_("Name of User"), blank=True, max_length=255) first_name = models.CharField(max_length=150, blank=True, verbose_name="first name") last_name = models.CharField(max_length=150, blank=True, verbose_name="last name") journal = models.ForeignKey("journal.Journal", on_delete=models.SET_NULL, verbose_name=_("Journal"), null=True, blank=True) collection = models.ManyToManyField("collection.Collection", verbose_name=_("Collection"), blank=True) def get_absolute_url(self): """Get url for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"username": self.username}) forms.py from django import forms from django.utils.translation import gettext_lazy as _ from wagtail.users.forms import UserEditForm, UserCreationForm from collection.models import Collection from journal.models import Journal class CustomUserEditForm(UserEditForm): journal = forms.ModelChoiceField(queryset=Journal.objects, required=False, label=_("Journal")) collection = forms.ModelMultipleChoiceField(queryset=Collection.objects.filter(is_active=True), required=True, label=_("Collection")) class CustomUserCreationForm(UserCreationForm): journal = forms.ModelChoiceField(queryset=Journal.objects, required=False, label=_("Journal")) collection = forms.ModelMultipleChoiceField(queryset=Collection.objects.filter(is_active=True), required=True, label=_("Collection")) base.py WAGTAIL_USER_EDIT_FORM = 'core.users.forms.CustomUserEditForm' WAGTAIL_USER_CREATION_FORM = 'core.users.forms.CustomUserCreationForm' WAGTAIL_USER_CUSTOM_FIELDS … -
Getting this error : FOREIGN KEY constraint failed in my django application
I have created a BaseUser model to create users and i have also created a Profile for every single user when new user gets created. But when i try to update the information's or try to delete the specific user from the admin panel i get this error :- [12/Jan/2024 15:05:29] "GET /admin/accounts/baseuser/16/change/ HTTP/1.1" 200 17895 [12/Jan/2024 15:05:30] "GET /static/admin/js/jquery.init.js HTTP/1.1" 200 347 Not Found: /favicon.ico Internal Server Error: /admin/accounts/baseuser/16/change/ Traceback (most recent call last): File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 313, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 688, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1889, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/home/mohit/okk/django_pinterest/myenv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1747, … -
what are some of the best Resources for Learning and making projects?
I was searching for some great resources for learning React, DSA, and Django all with some bigger Projects. I tried youtubeing but some only are good, if I get someone explaining better on youtube its also fine. other resource like udemy courses are also fine. -
FullCalendar I have the standard event model working, how do I add a dropdown to select additional data in the Javascript/Ajax area?
The events in the FullCalendar are just using fields: name, start and end as in the html-> $(document).ready(function () { var calendar = $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, events: '/list_events', selectable: true, selectHelper: true, editable: true, eventLimit: true, businessHours: true, select: function (start, end) { let title = prompt("Enter Event Title"); if (title) { var start = prompt("enter start", $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss")); var end = prompt("enter end", $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss")); $.ajax({ type: "GET", url: '/add_event', data: {'title': title, 'start': start, 'end': end}, dataType: "json", success: function (data) { calendar.fullCalendar('refetchEvents'); alert("Added Successfully"); }, error: function (data) { alert('There is a problem!!!'); } }); } }, Question: I would like the function to collect additional data such as status, venue and instructor, where status is a selection, and venue and instructor are DB lookups from Django event model My Event model: class Event(models.Model): name = models.CharField('Event Name', max_length=120) status = models.CharField(choices=EventStatus, default=EventStatus.PENDING, max_length=25) start = models.DateTimeField('start', default="2024-01-01 00:00:00") end = models.DateTimeField('end', default="2024-01-01 00:00:00") venue = models.ForeignKey(Venue, blank=True, null=True, on_delete=models.PROTECT) instructor = models.ForeignKey(Consultant, blank=True, null=True, on_delete=models.PROTECT) # 'name', 'start', 'end', 'venue', 'contact', 'instructor' def __str__(self): return self.name I see there are many code snippets and examples online, … -
when i export with the command flutter build app it generates complex javascript codes but i want only HTML,CSS , Javascript codes, is it Possible?
when i export with the command flutter build web it generates complex javascript codes , but i want only HTML,CSS and Javascript codes . is it Possible ? i have intended to make the front end with flutter and the back with django after exporting , but it is generating complex JS codes i cant get HTML tags and CSS styling , please help me if you have any idea i have tried with flutter build web but it is generating complex javascript codes -
Why do I need to configure volumes for running Django and MySQL in Docker containers?
I had a Django project with a MySQL database running on localhost and I wanted to migrate it to Docker containers. First I migrated the database. I didn't have any problems and I could connect to it from my Django project perfectly. However, when I migrated the Django project to another container, I couldn't connect it to the database. I would always get the following error: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") I tried all sorts of solutions and nothing worked. I was using the following docker-compose configuration: version: '3.9' services: my-db: build: ./localhost-db container_name: my-db ports: - 3306:3306 volumes: - my-db-vol:/var/lib/mysql my-server: build: . container_name: my-server ports: - 8000:8000 command: python3 manage.py runserver 0.0.0.0:8000 depends_on: - my-db volumes: my-db-vol: external: true Then I came across this blog post: https://dev.to/foadlind/dockerizing-a-django-mysql-project-g4m Following the configuration in the post, I changed my docker-compose file to: version: '3.9' services: my-db: build: ./localhost-db container_name: my-db ports: - 3306:3306 volumes: - /tmp/app/mysqld:/var/run/mysqld - my-db-vol:/var/lib/mysql my-server: build: . container_name: my-server ports: - 8000:8000 command: python3 manage.py runserver 0.0.0.0:8000 volumes: - /tmp/app/mysqld:/run/mysqld depends_on: - my-db volumes: my-db-vol: external: true Now everything works perfectly, but I can't figure out why adding /tmp/app/mysqld:/var/run/mysqld to … -
2 Django services with common Model
I'm developing some project that needs to be split into two separate Django services, but with one common database (and some of their own for each service). I know that I can provide the database as not default in both applications in settings.py. I know that I can create db_router in both services. I know there may not be the best architecture here. I know that I can make one of this services as "client" which requests another for some operations. But are these all possible solutions? What is the best practice? -
why update is not working when customising the save() in the modle class?
class Person(models.Model): SHIRT_SIZES = [ ("S", "Small"), ("M", "Medium"), ("L", "Large"), ] first_name = models.CharField("person's first name:", max_length = 30, help_text = "User First name") last_name = models.CharField("Person's Last Name:",max_length = 30, help_text = "User Last name") shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES, default = "S", help_text = "User shirt size") def __str__(self) -> str: return self.first_name + ' ' + self.last_name def full_name(self): return '%s %s' %(self.first_name, self.last_name) def get_absolute_url(self): return "/people/%i/" % self.id; def save(self, *args, **kwargs): self.first_name = "%s %s" %('Mr', self.first_name) return super().save(self, *args, **kwargs) Creating a new record is working fine but it's generating an error when updating the existing record. IntegrityError at /admin/members/person/14/change/ UNIQUE constraint failed: members_person.id Request Method: POST Request URL: http://127.0.0.1:8000/admin/members/person/14/change/ Django Version: 3.2.23 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: members_person.id Exception Location: C:\wamp\www\python\myproject\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\wamp\www\python\myproject\Scripts\python.exe Python Version: 3.6.6 Python Path: ['C:\\wamp\\www\\python\\vleproject', 'C:\\wamp\\www\\python\\myproject\\Scripts\\python36.zip', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\DLLs', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\lib', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64', 'C:\\wamp\\www\\python\\myproject', 'C:\\wamp\\www\\python\\myproject\\lib\\site-packages'] Server time: Fri, 12 Jan 2024 13:11:09 +0000 -
Django not updating latest date on form and website?
I'm doing a website using Django, it's hosted on AWS (EC2 with gunicorn for Django server, S3 + cluodfront for static files). I'm doing tests on several days before deployment, but I have an issue : the data on the website seems to not be updated when new values are coming. For exemple on one page : I have an insight with a total "files" value (each days, there are more files so the number is growing) I have a form with a date range (min and max date from the database) I have a div with a max date insight. The server is running for 3 days and the max date is the same as the first day (09/01), same for the insight : value for the 09/01. I've tried to set up a cache that's updated every day. Surprisingly, the update seems to work: if I print the cached value, it's correct and shows the last day, but on the website, nothing updates. The form always displays the maximum date as 09/01 and the insight seems to be frozen. How to solve this problem? In settings.py DEBUG is False. Here are the contents (shortened with the elements concerned) … -
Sorting data / refresh page with new query - Django5 ListView
I am trying to perform a query on the same page using Django. After selecting data from the dropdown and clicking the button, the information should be filtered accordingly. However, I couldn't find a solution to get the data after selecting from my dropdown and will refresh the page using Django. Is this possible? Here's my views.py class DocListView(ListView): model = Document template_name = 'docs/documents.html' paginate_by = 5 context_object_name = 'doc_list' def get_queryset(self): return Document.objects.all() -
Issue with Azure "django_auth_adfs" and Django built in Token Authentication (IsAdminUser)
I have a Django web app with built in Django Rest Framework. I would like to use the Api via Powershell script to update/create data on the database. The Web application will be accessed by users and they will authenticate via Microsoft login. Currently the authentication works fine, but I'm not able to post to database via Powershell using the token that I created within the Django Admin Portal (Admin User). I get a 401 UNAUTHORIZED. I can confirm the token is generated using Super user account. The api works when I remove permission_classes = [IsAdminUser] from the DRF Create View. When I don't exempt the API url and tries to Post it take me to Microsoft login page and if I exempt the url , I get an authorized call error. In short please guide me on how I can do a post request to a specific endpoint without logging or providing credentials, but just using token. I want to user Azure Authentication in conjunction with Django DRF token authentication. This the guide I referred for ADFS authentication - https://django-auth-adfs.readthedocs.io/en/latest/install.html Below is my settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-xxxx' DEBUG = True … -
Django unit test issue with thread and database interaction : database is being accessed by other users
I have a Django project with the following View : def base_task(): # do something def heavy_task(): # do something with interaction with a PostgreSQL database class MyView(generics.UpdateAPIView): def update(self, request, *args, **kwargs): message_to_return, heavy_task_needed = base_task() if heavy_task_needed thread = Thread(target=heavy_task) thread.start() return JsonResponse(message_to_return, status=201) This code returns a response to the client as fast as possible, and start some heavy processing on another thread. I have some unit tests for this code : class EndpointsTestCase(TestCase): fixtures = ["segment.json", "raw_user.json"] def test_1(self): c = Client() body = { #some data } response = c.put( path=f"/my/endpoint/", data=json.dumps(body), content_type="application/json", ) expected_body = to_json_comparable({ #some data }) self.assertEqual(response.content, expected_body) def test_2(self): c = Client() body = { #some data } response = c.put( path=f"/my/endpoint/", data=json.dumps(body), content_type="application/json", ) expected_body = to_json_comparable({ #some data }) self.assertEqual(response.content, expected_body) The issue I have is that, if multiple test cases trigger the heavy_task thread, my tests fail with this error : django.db.utils.OperationalError: database "my_db" is being accessed by other users DETAIL: There are X other sessions using the database. Likely due to the fact that a new test has been started before the thread of the previous test has terminated. How can I solve this issue, as … -
phone number and password not storing in the django admin
Hello I was trying to make a project and the phone number and password from the signup page is not storing but other things like name email are being registered.I tried checking it so many times but could not figure it out ` customer model `from django.db import models from django.core.validators import MinLengthValidator class Customer(models.Model): first_name = models.CharField(max_length=50, null=True) last_name = models.CharField(max_length=50, null=True) phone = models.CharField(max_length=15, null=True) email = models.EmailField(default="",null=True) password = models.CharField(max_length=500,null=True) def register(self): self.save() @staticmethod def get_customer_by_email(email): try: return Customer.objects.get(email=email) except: return False def isExists(self): if Customer.objects.filter(email = self.email): return True return False` views \`from django.shortcuts import render, redirect from django.http import HttpResponse from .models.product import Product from .models.category import Category from .models.customer import Customer def signup(request): if request.method == 'GET': return render(request, 'core/signup.html') else: postData = request.POST first_name = postData.get('firstname') last_name = postData.get('lastname') phone = postData.get('phone') email= postData.get('email') password =postData.get('password' ) customer= Customer(first_name= first_name, last_name= last_name, phone=phone, email=email, password= password) customer.register() return redirect('core:homepage') -
How to translate default Django admin panel to another language?
I use the default Django admin panel with jazzmin. I need the entire admin panel to be completely in Turkmen language. As far as I know, it is not supported in Django yet. How can I translate the entire admin panel to Turkmen? I tried to include these: from django.contrib import admin admin.site.index_title = "SmartLib" admin.site.site_header = "SmartLib Dolandyryş" admin.site.site_title = "Dolandyryş" But it is not enough. I need to translate everything. I also tried makemessages and compilemessages but they didn't generate .po files from the admin panel. -
Google Cloud Storage URL stripped from deployed build/index.html in Django/React on Google Cloud Run (GCR)
Here's the situation. I deploy a Django/React app to Google Cloud Run (GCR) with Docker and static files served over Google Cloud Storage (bucket) Everything is fine except a thing I haven't managed to figure out and I did so many trials that it's impossible to tell my attempts. I'm pretty sure the bucket and GCR service accounts are correct and have sufficient permissions. All necessary API's are activated. The command python manage.py collectstatic run in entrypoint.sh works and the files are uploaded correctly to the bucket. Also, I am totally new to this coming from a "classic" Full Stack PHP/MySQL/JS development environment. Here's the issue. When I run npm run build the /build/index.html shows the correct url to the static files (js/css) like so: src="https://storage.googleapis.com/my-app-bucket/staticfiles/static/js/main.xxx.js" When deployed it "strips" the main url part leaving /staticfiles/static/js/main.xxx.js and so it tries to call the files with the app url like so https://default-xxxxx.a.run.app/staticfiles/static/js/main.xxx.js which of course produces a 404. How can I tell my app to get these files from the bucket? Here are the commands I use to deploy: gcloud builds submit --tag us-east1-docker.pkg.dev/my-app/mbd-docker-repo/mbd-docker-image:my-tag and gcloud run deploy default-my-gcr-service \ --image us-east1-docker.pkg.dev/my-app/mbd-docker-repo/mbd-docker-image:my-tag \ --add-cloudsql-instances my-app:us-south1:my-app-db \ --set-secrets=INSTANCE_CONNECTION_NAME=INSTANCE_CONNECTION_NAME:1 \ --set-secrets=INSTANCE_UNIX_SOCKET=INSTANCE_UNIX_SOCKET:1 \ --set-secrets=DB_NAME=DB_NAME:3 … -
Check if the id is present in the JsonField(list) passed to OutRef during Django subquery filtering
If I have 2 models related through a JsonField(list),I am annotating a queryset of Foos with bars in this list class Foo(Model): bar_list = models.JSONField(default=list) class Bar(Model): id = IntegerField() bar_query = Bar.objects.filter(id__in=OuterRef('bar_list')).values("id")[:1] foos_with_bar_id = Foo.objects.all().annotate(task_id=Subquery(bar_query)) but it doesn't work. I get a error"django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near..." But when i relplace the "OuterRef" to a specified list, like[1,2,3], It works. So does OuterRef not support JsonField? -
what's (page = DEFAULT_PAGE) role in CustomPagination by DRF (django-rest-framework)?
For some reason, I could not understand the meaning and role of page=DEFAULT_PAGE in Custom Pagination in the DRF topic. Can you explain its role to me in the code below? Consider - pagination.py: from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response DEFAULT_PAGE = 9 DEFAULT_PAGE_SIZE = 9 class CustomPagination(PageNumberPagination): page = DEFAULT_PAGE page_size = DEFAULT_PAGE_SIZE page_size_query_param = 'page_size' def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'total': self.page.paginator.count, 'page': int(self.request.GET.get('page', DEFAULT_PAGE)), # can not set default = self.page 'page_size': int(self.request.GET.get('page_size', self.page_size)), 'results': data }) Note : This is important to me for setting up my app and I wanted to understand its role... Although I consulted the documentation, I didn't understand much about the role of page=PAGE_DEFAULT.