Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can not resolve djanngo model issue
I created three apps in my project, and when go to questions models it cannot find a model in Quiz models. please help. Im right in the directory where my manage.py is I tried to change path of my project interpreter, nothing changed -
Web stress testing, the pg encountered an exception, TCP/IP connections on port 5432?
I conducted basic stress testing on the django framework, and my View is as follows class HealthCheckView(APIView): def get(self, request, *args, **kwargs): try: Role.objects.filter().count() except Exception as e: return Response(status=499) return Response(status=status.HTTP_200_OK) I use the following command to start the web service: gunicorn myapp.wsgi:application -c myapp/settings/gunicorn.conf.py gunicorn.conf.py content is as follows: bind = f'0.0.0.0:{GUNICORN_PORT}' worker_class = 'eventlet' workers = 6 Then I used the ab tool for stress testing: ab -n 10000 -c 500 https://10.30.7.7/api/v1/healthz/ When the concurrency is 500, the result is good. When I continued to increase the number of concurrent requests, some of them were unable to connect to the database. django.db.utils.OperationalError: could not connect to server: Cannot assign requested address Is the server running on host "10.30.7.7" and accepting TCP/IP connections on port 5432? The database configuration file is as follows: max_connections = 4096 shared_buffers = 16GB effective_cache_size = 48GB maintenance_work_mem = 2GB checkpoint_completion_target = 0.9 wal_buffers = 16MB default_statistics_target = 100 random_page_cost = 4 effective_io_concurrency = 2 work_mem = 1MB huge_pages = try min_wal_size = 1GB max_wal_size = 4GB max_worker_processes = 20 max_parallel_workers_per_gather = 4 max_parallel_workers = 20 max_parallel_maintenance_workers = 4 How should I conduct the investigation? Reducing the number of concurrent requests can avoid … -
No url found for submodule path 'django/03_REL' in .gitmodules
No url found for submodule path 'django/03_REL' in .gitmodules The process '/usr/bin/git' failed with exit code 128 I'm encountering a build error in GitHub committing process. The error messages are above. I tried git submodule -v status and below is the result. usage: git submodule [--quiet] [--cached] or: git submodule [--quiet] add [-b <branch>] [-f|--force] [--name <name>] [--reference <repository>] [--] <repository> [<path>] or: git submodule [--quiet] status [--cached] [--recursive] [--] [<path>...] or: git submodule [--quiet] init [--] [<path>...] or: git submodule [--quiet] deinit [-f|--force] (--all| [--] <path>...) or: git submodule [--quiet] summary [--cached|--files] [--summary-limit <n>] [commit] [--] [<path>...] or: git submodule [--quiet] foreach [--recursive] <command> or: git submodule [--quiet] sync [--recursive] [--] [<path>...] or: git submodule [--quiet] absorbgitdirs [--] [<path>...] The file includes a .gitignore file and I don't know if it is a matter of a .gitignore file or if there are other reasons. -
Why custom clients might be ignored by unittest in Django?
Exploring Unittest, can't figure out why these tests ignore custom clients prepared in setUp() method and use the built-in self.client (== self.guest_client). Thus only the last test for anonimous user works properly. The same setUp() method works fine in other test files, as well as url constants. test file: User = get_user_model() NOTE_SLUG = 'note-slug' HOME_URL = reverse('notes:home') LOGIN_URL = reverse("users:login") SIGNUP_URL = reverse('users:signup') LOGOUT_URL = reverse('users:logout') NOTES_LIST_URL = reverse('notes:list') ADD_NOTE_URL = reverse('notes:add') NOTE_CONFIRM = reverse('notes:success') NOTE_URL = reverse('notes:detail', args=(NOTE_SLUG,)) NOTE_EDIT_URL = reverse('notes:edit', args=(NOTE_SLUG,)) NOTE_DELETE_URL = reverse('notes:delete', args=(NOTE_SLUG,)) class TestRoutes(TestCase): @classmethod def setUpTestData(cls): cls.url_list = ( HOME_URL, LOGIN_URL, SIGNUP_URL, LOGOUT_URL, NOTES_LIST_URL, ADD_NOTE_URL, NOTE_CONFIRM, NOTE_URL, NOTE_EDIT_URL, NOTE_DELETE_URL ) cls.author = User.objects.create(username='author') cls.note = Note.objects.create( title='Заголовок', text='Текст заметки', slug='note-slug', author=cls.author, ) def setUp(self): self.guest_client = Client() self.reader = User.objects.create(username='reader') self.authorized_client = Client() self.authorized_client.force_login(self.reader) self.author_client = Client() self.author_client.force_login(self.author) def test_pages_for_author(self): for url in self.url_list: with self.subTest(url=url): response = self.author_client.get(url) self.assertEqual(response.status_code, HTTPStatus.OK) def test_pages_for_auth_reader(self): for url in self.url_list[0:7]: with self.subTest(url=url): response = self.authorized_client.get(url) self.assertEqual(response.status_code, HTTPStatus.OK) for url in self.url_list[7:10]: with self.subTest(url=url): response = self.authorized_client.get(url) self.assertEqual(response.status_code, HTTPStatus.NOT_FOUND) def test_pages_for_anonymous(self): for url in self.url_list[0:4]: with self.subTest(url=url): response = self.guest_client.get(url) self.assertEqual(response.status_code, HTTPStatus.OK) for url in self.url_list[4:10]: with self.subTest(url=url): redirect_url = f'{LOGIN_URL}?next={url}' self.assertRedirects(self.guest_client.get(url), redirect_url) -
AssertionError at /api/v1/companies/
Class CompanySerializers missing "Meta.model" attribute I have been making an API using Django Rest Api Framework and it showing the above error whenever I run my app. My Serializers.py: from rest_framework import serializers from api.models import Company # Create Serializers here class CompanySerializers(serializers.HyperlinkedModelSerializer): class Meta: model: Company fields = "__all__" My model.py: from django.db import models # Create your models here. #Creating Company model class Company(models.Model): company_id = models.AutoField(primary_key= True) name = models.CharField(max_length=50) location = models.CharField(max_length= 50) about = models.TextField() type = models.CharField(max_length= 100, choices= (('IT','IT'), ('Non IT', 'Non_IT'), ('Mobiles_phones', 'Mobiles_phones'))) added_Date = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) My views.py: from django.shortcuts import render from rest_framework import viewsets from api.models import Company from api.serializers import CompanySerializers # Create your views here. class CompanyViewSet(viewsets.ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializers I have tried everything and couldn't able to resolve it. Kindly please someone look into this it will quite helpful. -
"driver failed programming external connectivity on endpoint" on docker compose up
I'm trying to run docker compose up on a remote server and I get this error: Attaching to academyloadcalculator_app, academyloadcalculator_db Error response from daemon: driver failed programming external connectivity on endpoint academyloadcalculator_app (0f08a0e692314b5845afb52249ec4777f9699375be1cb9d719e9f49d1382a225): (iptables failed: iptables --wait -t filter -A DOCKER ! -i br-454388c834c8 -o br-454388c834c8 -p tcp -d 172.18.0.3 --dport 8000 -j ACCEPT: iptables: No chain/target/match by that name. However when I do the same on Windows it runs fine. Containers: academyloadcalculator_db - container with postgres academyloadcalculator_app - container with django Script to run server: #!/bin/bash cd src python3 manage.py makemigrations python3 manage.py migrate python3 manage.py runserver 0.0.0.0:8000 Dockerfile FROM python:3.11-slim COPY ./src /app/src COPY ./requirements.txt /app COPY ./scripts /app/scripts WORKDIR /app RUN pip3 install -r requirements.txt EXPOSE 8000 docker-compose.yaml version: "3.11" services: db: image: postgres:latest container_name: academyloadcalculator_db environment: POSTGRES_PASSWORD: "1234" POSTGRES_DB: "academyloadcalculator" POSTGRES_USER: "postgres" expose: - 5432 volumes: - data:/var/lib/postgresql/data app: build: context: ./ dockerfile: Dockerfile container_name: academyloadcalculator_app ports: - "8000:8000" depends_on: - db command: ["/app/scripts/startApp.sh"] volumes: data: docker ps: shows that only Postgres container runs fine but container with django app isn't present Server details: OS: Ubuntu 22.04.2 LTS x86_64 Host: KVM/QEMU (Standard PC (i440FX + PIIX, 1996) pc-i440fx-bionic) Kernel: 5.15.0-73-generic Uptime: 2 hours, 47 mins Packages: … -
Images are not displayed on django
I have a problem with path image in django, When I put in the path from the model (item.img) and start the server, I don't see the image because the image path doesn't contain /media/.but if I add /media/ before {{item.url}} everything is going right I can't figure out what I'm doing wrong My code: -setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' AUTH_USER_MODEL = 'authentication.CustomUser' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') -urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('items.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=sett -html <div class="main__column"> <div class="main__item item"> <div class="item__img"> {% for img in p.image_set.all %} {{img.main_image}} <img src="{{img.main_image}}" alt=""> {%endfor%} </div> <div class="item__body"> <div class="item__name">{{p.name}}</div> <div class="item__descriptions">{{p.descriptions}}</div> <div class="item__price">{{p.price}}</div> <div class="item__in_stock">{{p.in_stock}}</div> </div> </div> </div> I have looked for a solution to the problem in other forums. I am waiting for someone's help -
In Django, can you filter a queryset by a parent (uses ForeignKey field) model's field value?
Let's say you have models defined for Transaction, Category, and TransactionDetail, like so: class Transaction(models.Model): details = models.ForeignKey(TransactionDetails, verbose_name="Transaction Details", on_delete=models.PROTECT, default='',null=True) category = models.ForeignKey(Category, verbose_name="Transaction Category", on_delete=models.PROTECT, default='') class Category(models.Model): name = models.CharField(max_length=255, verbose_name="Category Name", default="") class TransactionDetails(models.Model): value = models.CharField(max_length=255, verbose_name="Transaction Detail", default="") In views.py I am trying to figure out how to filter TransactionDetails objects that are attached to a Transaction.details field AND have a specific Transaction.Category.name. In other words, I'd like to return a queryset of TransactionDetails that are related to Transaction objects with a category.name of "uncategorized". I understand how to use the objects manager filter for the other way around: uncatTransactions = Transaction.objects.filter(category__name="Uncategorized") But am unsure how this would be done for TransactionDetails: uncategorizedTrxDetails = TransactionDetails.objects.filter(referenceToParentUsingForeignKey__category__name="Uncategorized") -
Django CSRF token missing in form submission despite including it
I am working on a Django project where I have a form to verify a phone number using Twilio's API. However, I'm encountering an issue where the CSRF token is missing in the form submission, resulting in a "CSRF token missing" error. I have already included the {% csrf_token %} template tag inside the element in my HTML template. I have also verified that the django.middleware.csrf.CsrfViewMiddleware middleware is enabled in my Django settings. @login_required def verify_phone_number(request): if request.method == 'POST': # Code to initiate phone number verification using Twilio's API # Code to Return an HTTP response with the HTML content when verification request wasnt sent html_content = """ return HttpResponse(html_content) else: # Return an HTTP response with the HTML content html_content = """ <!DOCTYPE html> <html> <head> <title>Verify Phone Number</title> </head> <body> <h1>Verify Your Phone Number</h1> <form method="post"> {% csrf_token %} <label for="phone_number">Phone Number:</label> <input type="text" id="phone_number" name="phone_number" required> <button type="submit">Verify</button> </form> </body> </html> """ return HttpResponse(html_content) -
How to show comment on blogpost with slug instead of pk
I want to show the comment underneath an article, but I use a slug instead of a pk. I got the following error: IntegrityError at /blogpost-2/comment/ NOT NULL constraint failed: blog_comment.post_id This is my code: #models.py `class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name)` #views.py `class AddCommentView(CreateView): model = Comment form_class = CommentForm template_name = "add_comment.html" #fields = '__all__' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) success_url = reverse_lazy('blog')` #urls.py `from django.urls import path from . import views from .views import BlogView, ArticleView, CategoryView, AddCommentView urlpatterns = [ path('<slug:slug>', ArticleView.as_view(), name='blogpost'), path('blog/', BlogView.as_view(), name='blog'), path('categorie/<str:cats>/', CategoryView, name='category'), path('<slug:slug>/comment/', AddCommentView.as_view(), name='add_comment'), ]` #template add_comment.html `{% extends 'base.html' %} {% load static %} {% block content %} <h1>Voeg een reactie toe..</h1> <div class="form-group"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-primary">Voeg toe</button> </form> </div> {% endblock %}` I tried this code, but doesn't work... def form_valid(self, form): form.instance.post_slug = self.kwargs['slug'] return super().form_valid(form) -
Azure webapp doesn't start and logs not showing
i Just deployed a Django app from Azure Devops Pipeline to an Azure webapp, the Pipeline runs fine, but it shows an error when try access using web browse: "Application Error" . The logs from bash shell don't tell much neither. [![enter image description here][2]][2] The Stream logs shows that the app tries to start but then stops. 2023-10-11T19:18:15.793Z INFO - 3.10_20230810.1.tuxprod Pulling from appsvc/python 2023-10-11T19:18:16.054Z INFO - Digest: sha256:6e7907b272357dfda9a8c141b01fc30851ffc4448c6c41b81d6d6d63d2de0472 2023-10-11T19:18:16.064Z INFO - Status: Image is up to date for mcr.microsoft.com/appsvc/python:3.10_20230810.1.tuxprod 2023-10-11T19:18:16.150Z INFO - Pull Image successful, Time taken: 0 Minutes and 1 Seconds 2023-10-11T19:18:16.450Z INFO - Starting container for site 2023-10-11T19:18:16.451Z INFO - docker run -d --expose=8000 --name webapp-firma-backend_1_9d3d260f -e WEBSITES_PORT=8000 -e WEBSITE_SITE_NAME=webapp-firma-backend -e WEBSITE_AUTH_ENABLED=False -e PORT=8000 -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=webapp-firma-backend.azurewebsites.net -e WEBSITE_INSTANCE_ID=0a01d13b0c74e2087a0a20c4078e93f91439134653f92861a8deef4a0aa726ab -e HTTP_LOGGING_ENABLED=1 -e WEBSITE_USE_DIAGNOSTIC_SERVER=False appsvc/python:3.10_20230810.1.tuxprod sh start.sh 2023-10-11T19:18:20.351Z INFO - Initiating warmup request to container webapp-firma-backend_1_9d3d260f for site webapp-firma-backend 2023-10-11T19:18:19.698796823Z _____ 2023-10-11T19:18:19.698834524Z / _ \ __________ _________ ____ 2023-10-11T19:18:19.698839824Z / /_\ \\___ / | \_ __ \_/ __ \ 2023-10-11T19:18:19.698843324Z / | \/ /| | /| | \/\ ___/ 2023-10-11T19:18:19.698846424Z \____|__ /_____ \____/ |__| \___ > 2023-10-11T19:18:19.698849924Z \/ \/ \/ 2023-10-11T19:18:19.698853024Z A P P S E R V I C E O N L I N … -
Django form bringing unselected data
Am creating a django form that enables me enter student marks but it works best for the start and it then brings students I didn't select . The project that collects student marks but am trying to make a form that inputs marks after selecting the students on one form but this works well before I enter any marks but it then brings all the students whose marks I've already entered plus those I select for new entries. In my views.py I have that @login_required def create_result(request): students = Student.objects.all() if request.method == "POST": # after visiting the second page if "finish" in request.POST: form = CreateResults(request.POST) if form.is_valid(): subjects = form.cleaned_data["subjects"] session = form.cleaned_data["session"] term = form.cleaned_data["term"] students = request.POST["students"] results = [] for student in students.split(","): stu = Student.objects.get(pk=student) if stu.current_class: for subject in subjects: check = Result.objects.filter( session=session, term=term, current_class=stu.current_class, subject=subject, student=stu, ).first() if not check: results.append( Result( session=session, term=term, current_class=stu.current_class, subject=subject, student=stu, ) ) Result.objects.bulk_create(results) return redirect("Results:new-results") # after choosing students id_list = request.POST.getlist("students") if id_list: form = CreateResults( initial={ "session": request.current_session, "term": request.current_term, } ) studentlist = ",".join(id_list) return render( request, "Results/resultsentry1.html", {"students": studentlist, "form": form, "count": len(id_list)}, ) else: messages.warning(request, "You didnt select any … -
Django channels with react axios runs twice
I use django channels and react to create a chat app. I have two models. Message and chat. Message just contains each message users have send, and chat contains more information about the chat of 2 users. When a new message is created I display it on screen and then create a new model of message with axios. After that I also create a chat one. My problem is that sometimes 2 messages are created at one time even if only one is displayed on the screen. I have noticed that react doesn't re-render so I don't know what causes this. Also it is inconsistent, some times only one is made and when the other user writes a message they start doubling. useEffect(()=> { let ran = true; chatSocket.onmessage = function(e) { if (ran == true) { const data = JSON.parse(e.data); setMessages(old => [...old, <div id={data.sendby.username == currentUser[0]?.username ? 'ownUser' : 'elseUser'}><p ref={oneRef} data-username={data.sendby == currentUser[0]?.username ? 'ownUser' : 'elseUser'}>{data.message}</p></div>]) axios.post('http://127.0.0.1:8000/create_message/', { headers: { 'Content-type': 'application/json' }, message:data.message }).then(res=>{ const formData = new FormData() formData.append('chat_room',roomName) formData.append('sender',JSON.stringify(data.sendby)) console.log(formData.forEach(el => console.log(el))) axios.post('http://127.0.0.1:8000/create_chat/', formData, { headers: { 'Content-type': 'multipart/form-data' } }).then(res=>console.log(res)) }) } } return () => { ran = false; }; },[currentUser]) … -
Django - setting a model pk to None and saving returns "ValueError: Cannot force an update in save() with no primary key."
I have already figured this out but I could not find an answer to this and will post because somebody might find it helpful. Here is the code that was causing problems: models.py class SModelQuerySet(models.QuerySet): def stubbed_outputs(self): return self.defer("outputs").annotate( has_outputs=models.Case( models.When( models.Q(~models.Q(outputs={}) & models.Q(outputs__isnull=False)), then=True, ), default=False, output_field=models.BooleanField(), ) ) def for_user(self, user): return self.filter(user=user) class SModelManager(models.Manager): def get_queryset(self): return SModelsQuerySet(self.model, using=self._db).stubbed_outputs() def for_user(self, user): return self.get_queryset().for_user(user) class OutputsManager(models.Manager): def get_queryset(self): return super().get_queryset().only("outputs") def for_user(self, user): return self.get_queryset().filter(user=user) class SModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True) name = models.CharField(max_length=50) description = models.CharField(max_length=500, null=True, blank=True) inputs = models.JSONField(default=dict) outputs = models.JSONField(default=dict) objects = SModelManager() outputs_objects = OutputsManager() class Meta: verbose_name_plural = "scientific models" db_table = "smodels" managed = False def __str__(self): return self.name views.py class SharedModelViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) serializer_class = serializers.SharedModelSerializer @action(detail=True, methods=["post"]) def save(self, request, pk=None): shared_model = self.get_object() model = get_object_or_404( models.SModel.objects.filter(user=shared_model.share_from), pk=shared_model.model_to_share_id, ) model.pk = None model.user_id = shared_model.share_to.id model.save() shared_model.delete() return Response( serializers.SModelSerializer(model).data, status=status.HTTP_200_OK ) When this view was trying to save, I was getting an error like this: "ValueError: Cannot force an update in save() with no primary key." I could not figure this out and it was working a few weeks ago. -
Django, DRF + React, Axios. Error 403 Forbidden
Sorry for my english speaking skills. I have such a problem, I make a website using django, drf and react with axios. So i have this code: models.py from django.db import models from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class AppUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('An email is required.') if not password: raise ValueError('A password is required.') email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password=None): if not email: raise ValueError('An email is required.') if not password: raise ValueError('A password is required.') user = self.create_user(email, password) user.is_superuser = True user.save() return user class AppUser(AbstractBaseUser, PermissionsMixin): user_id = models.AutoField(primary_key=True) email = models.EmailField(max_length=50, unique=True) username = models.CharField(max_length=50) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = AppUserManager() def __str__(self): return self.username serializers.py from rest_framework import serializers from django.contrib.auth import get_user_model, authenticate from django.core.exceptions import ValidationError UserModel = get_user_model() class UserRegisterSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = '__all__' def create(self, clean_data): user_obj = UserModel.objects.create_user(email=clean_data['email'], password=clean_data['password']) user_obj.username = clean_data['username'] user_obj.save() return user_obj class UserLoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() ## def check_user(self, clean_data): user = authenticate(username=clean_data['email'], password=clean_data['password']) if not user: raise ValidationError('пользователь не найден') return user class UserSerializer(serializers.ModelSerializer): class Meta: model = … -
recursive dependency involving fixture (django, pytest)
Just got started with pytest, can't figure out what seems to be the problem here. Fixtures work fine in other test files. Can't figure out what dependancies are triggered partial error msg: E recursive dependency involving fixture 'author_client' detected > available fixtures: _dj_autoclear_mailbox, _django_clear_site_cache, _django_db_helper, _django_db_marker, _django_set_urlconf, _django_setup_unittest, _fail_for_invalid_template_variable, _live_server_helper, _template_string_if_invalid_marker, admin_client, admin_user, async_client, async_rf, author, author_client, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, client, comment, db, django_assert_max_num_queries, django_assert_num_queries, django_capture_on_commit_callbacks, django_db_blocker, django_db_createdb, django_db_keepdb, django_db_modify_db_settings, django_db_modify_db_settings_parallel_suffix, django_db_modify_db_settings_tox_suffix, django_db_modify_db_settings_xdist_suffix, django_db_reset_sequences, django_db_serialized_rollback, django_db_setup, django_db_use_migrations, django_mail_dnsname, django_mail_patch_dns, django_test_environment, django_user_model, django_username_field, doctest_namespace, form_data, homepage_news, live_server, mailoutbox, monkeypatch, news, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, rf, second_comment, settings, subtests, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory, transactional_db > use 'pytest --fixtures [testpath]' for help on them. D:\Dev\django_testing\venv\lib\site-packages\_pytest\fixtures.py:353 ========================================================================================================= short test summary info ========================================================================================================== ERROR news/pytest_tests/test_routes.py::test_pages_availability[/-client-HTTPStatus.OK] ERROR news/pytest_tests/test_routes.py::test_pages_availability[/auth/login/-client-HTTPStatus.OK] ERROR news/pytest_tests/test_routes.py::test_pages_availability[/auth/signup/-client-HTTPStatus.OK] ERROR news/pytest_tests/test_routes.py::test_pages_availability[/auth/logout/-client-HTTPStatus.OK] ERROR news/pytest_tests/test_routes.py::test_pages_availability[/news/1/-client-HTTPStatus.OK] ERROR news/pytest_tests/test_routes.py::test_pages_availability[/edit_comment/1/-author_client-HTTPStatus.OK] ERROR news/pytest_tests/test_routes.py::test_pages_availability[/delete_comment/1/-author_client-HTTPStatus.OK] test outtake: COMM_ID = 1 NEWS_ID = 1 HOME_URL = reverse('news:home') LOGIN_URL = reverse("users:login") SIGNUP_URL = reverse('users:signup') LOGOUT_URL = reverse('users:logout') NEWS_URL = reverse('news:detail', args=(NEWS_ID,)) COMM_EDIT_URL = reverse('news:edit', args=(COMM_ID,)) COMM_DELETE_URL = reverse('news:delete', args=(COMM_ID,)) ANONIMOUS_USER = pytest.lazy_fixture('client') AUTH_USER = pytest.lazy_fixture('admin_client') AUTHOR_USER = pytest.lazy_fixture('author_client') @pytest.mark.django_db @pytest.mark.parametrize( 'url, client, response_status', ( (HOME_URL, ANONIMOUS_USER, HTTPStatus.OK), (LOGIN_URL, ANONIMOUS_USER, HTTPStatus.OK), (SIGNUP_URL, ANONIMOUS_USER, HTTPStatus.OK), (LOGOUT_URL, ANONIMOUS_USER, HTTPStatus.OK), (NEWS_URL, ANONIMOUS_USER, HTTPStatus.OK), (COMM_EDIT_URL, AUTHOR_USER, … -
Datepicker not highlighting specified dates
I am trying to highlight an array of dates in a date picker, however i cannot seem to get it working. I know my jQuery is loading in the browser. Any and all help appreciated. class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ('booking_date', 'booking_time', 'number_attending') widgets = { 'booking_date': DateInput(attrs={'type': 'date', 'id': 'datepicker'}) } script.js var dates = ['14-10-2023', '15-10-2023', '16-10-2023']; $('#datepicker').datepicker ({ beforeShowDay: function (date) { var string = jQuery.datepicker.formatDate('dd-mm-yyyy', date); if ($.inArray(string, dates) == -1) { return [true, 'highlighted-date']; } else { return [true, '']; } }, }); css .highlighted-date { color: red; } script tags <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous" ></script> <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js" integrity="sha256-6XMVI0zB8cRzfZjqKcD01PBsAy3FlDASrlC8SxCpInY=" crossorigin="anonymous" ></script> -
Django | How to query foreignkey and return only one object on a specific key (prefetch)
I am having a headache writing a query :slight_smile: That’s my models: `class Mission(models.Model): machine = models.ForeignKey(Machine, on_delete=models.CASCADE, related_name="missions") start_dt = models.DateTimeField(null=False) longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True) latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True) @cached_property def timezone(self) -> datetime.tzinfo: timezone_str = get_tz(float(self.longitude), float(self.latitude)) return pytz.timezone(timezone_str)` and `class Machine(models.Model): name = models.CharField(max_length=12, null=False, unique=True) created_at = models.DateTimeField(_("created at"), auto_now_add=True) updated_at = models.DateTimeField(_("updated at"), auto_now=True)` I want to make a query with all the machines and for each machine a last_mission field where I have my last mission. like: machine.last_mission.timezone ... .I am completely stuck doing it with the django ORM. that’s my postgres query that doesn’t do exactly what I want as there is no last_mission key and not the model property. Thanks a lot for you help :slight_smile: select * from machines_machine machine, missions_mission mission where (mission.machine_id, mission.start_dt) in (select mission.machine_id as machine_id, Max(mission.start_dt) as start_dt from missions_mission mission group by mission.machine_id order by mission.machine_id) -
django, how to delete all the sessions per user
I have the below config in settings.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', ] SESSION_ENGINE = "django.contrib.sessions.backends.cache" So, we are using cache for session management, but not database. There is already existing solution for delete from DB Most optimized way to delete all sessions for a specific user in Django? but if session is cache, do we have a good way to delete user sessions by user name? Thanks in advance. I did not find a proper way to find the session details based on user name, from django code, I see cache key is created based on some random key, so not keyed to user name, so not sure how to achieve this? -
learning Django+Vite+Vue
Today, I have some reflections on learning Django+Vite+Vue. At first, I didn't understand why there were templates in Django but they weren't needed. Later on, I gradually understood that it was possible to simply use view and route as the backend and use Ajax and other technologies to obtain data. However, I didn't understand why I needed to use the django-vite package to merge the Vue project with Django. What were the advantages of this approach. Can't we directly obtain the data in the Vue project by visiting the website -
Merge multiple database table lines into one
Note: I am currently developing an application in Django using SQLite as my database, but I'm planning to migrate to IBM DB2 later, so a generic solution is preferred. Problem statement: I would like to merge rows in a parent table, that will update foreign values in children tables. I am looking for a generic solution that has the best DB practices. If a solution specific to Django models is achievable, it is also valid for solving the problem. Example: Suppose I have two artists in table artist, each one with one song each: PRAGMA foreign_keys = ON; CREATE TABLE artist( artistid INTEGER PRIMARY KEY, artistname TEXT ); CREATE TABLE track( trackid INTEGER PRIMARY KEY, trackname TEXT, trackartist INTEGER REFERENCES artist(artistid) ON UPDATE CASCADE ); insert into artist(artistid, artistname) values (1, 'Prince'); insert into artist(artistid, artistname) values (2, 'The Artist (Formerly Known as Prince)'); insert into track(trackid, trackname, trackartist) values (1, 'Purple Rain', 1); insert into track(trackid, trackname, trackartist) values (2, 'Dolphin', 2); artist | artistid | artistname | |:-------- |:------------------------------------- | | 1 | Prince | | 2 | The Artist (Formerly Known as Prince) | track | trackid | trackname | trackartist | |:------- |:----------- |:------------ | | … -
Python Django + postgresSQGl problem with login function
my problem it's problem with authenticate login. My code: class UsersPass(models.Model): id_user = models.IntegerField(null=False,primary_key=True) username = models.CharField(max_length=50) password = models.CharField(max_length=50)` views.py def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) print('haslo',password) if user: login(request, user) return redirect('main_view') else: return HttpResponse("Account not active or invalid login details") else: return render(request, 'main.html', {})` and urls.py path("",views.index,name='index'), path("main/",views.main_view, name='main_view'), path('login/', views.user_login, name='user_login'), Password and login are correct get from database. Print showing correct password. I don't have warning in console, but login function not working. Every time login ending incorrect with message "Account not active or invalid login details". I don;t know where is problem... I checked the connection to the database many times, changed passwords and logins, regardless of whether I entered the correct data or not, I could not log in. -
django.db.utils.ProgrammingError: column "id" referenced in foreign key constraint does not exist or multiple primary key for table is not allowed
Django4 on Postgres14. Newest version 2023 nov. this bug has been troubling me all day, I scanned though django GitHub issues on django projects research whole lot on SO and other FQA platforms asked gpt did not find a helpful solution. Hence write a guild that may facilitate visitor in future. -
Django application can access DB models but Pytest can't (invalid object name)
I'm using Pytest to write unit tests for a Django application. The application itself has no issue working with its databases, and it can read and write data completely fine with any method. When testing, database access using a cursor object works totally fine as well. However, whenever I try to access one of the databases in a test via a model object, I get this error: django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name '<table I'm trying to access>'. (208) (SQLExecDirectW)") Here's a minimal test that causes this issue - it produces the error above, using the table name Students_with_Holds: @pytest.mark.django_db(databases=['Coursematch']) def test_db_access(self): testobj = StudentsWithHolds.objects.using('Coursematch').create( person_id_number = 'testPIDnum', hold_type_code = 'test' ) assert testobj.person_id_number == 'testPIDnum' assert testobj.hold_type_code == 'test' Attempting to perform the exact same procedure using a cursor object, as shown below, does not cause the issue: @pytest.mark.django_db(databases=['Coursematch']) def test_db_access_cursor(self): with connections['Coursematch'].cursor() as cursor: insert_query = """ INSERT INTO Coursematch.dbo.Students_with_Holds (person_id_number,hold_type_code) VALUES ('testPIDnum','test') """ cursor.execute(insert_query) check_query = """ SELECT person_id_number,hold_type_code FROM Coursematch.dbo.Students_with_Holds WHERE person_id_number = 'testPIDnum' """ cursor.execute(check_query) assert cursor.fetchone() == ('testPIDnum','test') Any suggestions on how to stop this from happening? I've made sure that my models are all migrated, and that … -
connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed when i want to connect to django database container from celery task
I'm working on a django application with docker. I have a celery container which uses another redis container as brocker and backend. My postgres database is also in another container. Everything works well. But when I try to perform database operations in tasks, celery returns me: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed here is my docker-compose version: '3' services: app: container_name: ozangue build: context: . command: > sh -c "python manage.py wait_for_db && python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - ./electron:/electron - ./data/web:/vol/web environment: - SECRET_KEY=devsecretkey - DEBUG=1 - DB_HOST=db - DB_NAME=xxxxx - DB_USER=xxxxxx - DB_PASS=ozanguedb@2022 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 depends_on: - db - redis celery: container_name: celery-worker restart: always build: context: ./celery command: celery -A electron worker -l info -E depends_on: - app - redis redis: image: redis:7.0.5-alpine container_name: redis expose: - 6379 db: image: postgres:13-alpine container_name: database environment: - POSTGRES_DB=xxxxxxxx - POSTGRES_USER=xxxxxxx - POSTGRES_PASSWORD=xxxxxxxx celery.py os.environ.setdefault("DJANGO_SETTINGS_MODULE","electron.settings") app = Celery('electron', broker='redis://redis:6379/0',backend='redis://redis:6379/0') app.config_from_object("django.conf:settings",namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) settings CELERY_BROKER_URL = os.environ.get("CELERY_BROKER","redis://redis:6379/0") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER","redis://redis:6379/0") CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Libreville' How to solve this problem please?