Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-debug-toolbar configure INTERNAL_IPS for docker, compatible ip6
I just got django-debug-toolbar to work in Docker, but with a bit of a hack. The official instructions say if DEBUG: import socket # only if you haven't already imported this hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[: ip.rfind(".")] + ".1" for ip in ips] + ["127.0.0.1", "10.0.2.2"] However I saw no toolbar. In my template html I printed {{request.META.REMOTE_ADDR}} and noticed that it was an IP6 address. So I changed the above INTERNAL_IPS logic to if DEBUG: hostname, _, ips = socket.gethostbyname_ex (socket.gethostname()) ips = [ip[:ip.rfind(".")] + ".1" for ip in ips] INTERNAL_IPS += ips INTERNAL_IPS += ['::ffff:'+ip for ip in ips] This works but it feels hacky. Is there a better way to do this? -
find alternative to celery-beat to run slow tasks
I have a problem with a celery task that I have to run every 30 seconds. The task consists of connecting through ModbusTCP to a system to read some values. The problem is that I have to read these values from several systems and in 30s it is not able to finish the execution of all of them. As at the moment I do it is through celery-beat I execute a task that consists of a loop that goes through all the systems to which I have to connect to read the data. The connection attempt sometimes takes a while and that is what causes that in 30 seconds I don't have time to execute the whole loop. Is there any alternative to celery-beat that can fit the functionality I am looking for? Thanks! Try to find a solution for the problem or any alternative to solve my situation -
Django REST Framework Viewset Executes Actions Multiple Times and Shows 'None' for GET Requests
I have a Django REST framework viewset with multiple actions such as list, create, and more. When I send a GET request, I noticed that some actions are executed multiple times, and the action is sometimes set to "None." Can anyone help me understand why this is happening and how to resolve it? Here is my view code for reference: Url : path( "question/questionnaire/<int:questionnaire_id>/", QuestionModelViewSet.as_view({"get": "list", "post": "create"}), name="question_R", ), path( "question/<int:pk>/", QuestionModelViewSet.as_view( { "get": "retrieve", "delete": "destroy", "patch": "partial_update", "put": "update", } ), name="question_URD", ), permission : class IsStaffDoctorOrIsStaffHumanResource(permissions.BasePermission): def has_permission(self, request, view): # Check if the user belongs to the "staff_human_resource" group return request.user.groups.filter(name="staff_doctor").exists() or request.user.groups.filter(name="staff_human_resource").exists() View : class QuestionModelViewSet(viewsets.ModelViewSet): pagination_class = LargePagination def get_permissions(self): if self.action == "retrieve" or self.action == "list": permission_classes = [IsStaffDoctorOrIsStaffHumanResource] else: permission_classes = [DjangoModelPermissions] return [permission() for permission in permission_classes] def get_queryset(self): print(self.action) if self.action == "retrieve" or self.action == "update" or self.action == "partial_update" or self.action == "delete" or self.action == None : pk = self.kwargs.get("pk") data = Question.objects.filter(pk=pk) return data if self.action == "list" or self.action == "create": questionnaire_id = self.kwargs.get("questionnaire_id") data = Question.objects.filter(questionnaire=questionnaire_id) return data else: pk = self.kwargs.get("pk") data = Question.objects.filter(pk=pk) return data def get_serializer_class(self): if self.action == … -
what is local variable 'post' referenced before assignment?
I am making a blog with Django and it keeps showing this error to me while I followed the tutorial correctly and the person I am using his tutorial is not getting the same error where did I go wrong? plus some of the code like "post" and "request" are gray why?? Thanks in advance from django.shortcuts import render, redirect, get_object_or_404 from .forms import postform from .models import post # Create your views here. def detail(request, id): post = get_object_or_404(post, pk=id) return render(request, "posts/detail.html", {"post": post }) def delete(request, id): post = get_object_or_404(post, pk=id) post.delete() return redirect("/") def new(request): if request.method == "POST": form = postform(request.POST) if form.is_valid(): form.save() return redirect("/") else: form = postform() return render(request, "posts/new.html", {"form": form }) -
sorl thumbnail with cloudinary remote storage
Can't seem to find any info regarding using sorl.thumbnail with cloudinary. I managed to make it kinda work, but it generates thumbs on each reload which is obviously not right. For the information, I use cloudinary for media files only. -
Филтр данных для экспорта в excel [closed]
я вкрутил кнопку сохранения в экзел из базы данных. теперь нужно чтобы эта кнопка принимала все фильтры применённые в dashboard в теге table вот html представления <table class="table table-hover table-bordered"> <thead class="table-light"> <tr> <th scope="col"> ID </th> <th scope="col"> Адресс размещения </th> <th scope="col"> Тип </th> <th scope="col"> Категория </th> <th scope="col"> № Инвентаря </th> <th scope="col"> Дата эксплуатации </th> <th scope="col"> Наименование инвентаря </th> <th scope="col"> Состояние </th> <th scope="col"> Редактировать </th> </tr> </thead> <tbody> {% if page_obj %} {% for record in page_obj %} <tr> <td> {{record.id}} </td> <td> {{record.depart}} </td> <td>{{record.types}} </td> <td> {{record.category}} </td> <td> {{record.invent_number}} </td> <td> {{record.day}} </td> <td> {{record.name}} </td> <td> {{record.state}} </td> <td> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#recordModal{{ record.id }}">Редакт</button> <!-- Modal --> <div class="modal fade" id="recordModal{{ record.id }}" tabindex="-1" role="dialog" aria-labelledby="recordModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="recordModalLabel">Информация о записи</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p><strong>Департамент:</strong> {{record.depart}}</p> <p><strong>№ кабинета:</strong> {{record.number}}</p> <p><strong>Категория:</strong> {{record.category}}</p> <p><strong>Тип:</strong> {{record.types}}</p> <p><strong>Ответственный:</strong> {{record.otvet}}</p> <p><strong>№ Инвентаря:</strong> {{record.invent_number}}</p> <p><strong>Дата эксплуатации:</strong> {{record.day}}</p> <p><strong>Наименование инвентаря:</strong> {{record.name}}</p> <p><strong>Начальная цена:</strong> {{record.price}}</p> <p><strong>Коментарии:</strong> {{record.info}}</p> <p><strong>Пользователь:</strong> {{record.cr_user}}</p> <p><strong>Дата создания:</strong> {{record.date}}</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Закрыть</button> <a href="{% … -
Why the blockquotes section in RichtextuploadingField in django admin is not working?
When I am trying to add blockquotes in my blog details page from Django admin that time I add blockquotes in Django admin and even i saved it but the normal texts are not being the blockquotes in that details page .... and here is my blog-single.html page {% extends "base.html" %} {% load static %} {% static "images" as baseUrl %} {% block title %}Orbitor{% endblock %} <!--header block --> {% block header %} <!-- Slider Start --> <section class="section blog-wrap"> <div class="container"> <div class="row justify-content-center align-items-center"> <div class="single-blog-item text-center"> <img src="{{post.thumbnail.url}}" alt="" class="img-fluid rounded" style="max-width: 500px; max-height: 600px;"> <div class="blog-item-content mt-4"> <h2 class="mt-3 mb-3 text-md">{{post.title}}</h2> <div class="blog-item-meta mb-5"> <span class="text-muted text-capitalize mr-3"><i class="ti-pencil-alt mr-2"></i>{{post.category}}</span> <span class="text-black text-capitalize mr-3"><i class="ti-time mr-1"></i>{{post.pub_date}}</span> </div> </div> </div> </div> <p class="lead mb-4">{{post.head0}}</p> {{ post.head1|safe }} <div class="tag-option mt-5 clearfix"> <ul class="row justify-content-center align-items-center"> <li class="list-inline-item"> Share: </li> </ul> <ul class="tag-option mt-5 clearfix d-flex justify-content-center align-items-center"> <li class="list-inline-item"><a href="#" target="_blank"><i class="fab fa-facebook-f fa-2x" aria-hidden="true"></i></a></li> <li class="list-inline-item"><a href="#" target="_blank"><i class="fab fa-twitter fa-2x" aria-hidden="true"></i></a></li> <li class="list-inline-item"><a href="#" target="_blank"><i class="fab fa-pinterest-p fa-2x" aria-hidden="true"></i></a></li> <li class="list-inline-item"><a href="#" target="_blank"><i class="fab fa-instagram fa-2x" aria-hidden="true"></i></a></li> </ul> </div> <section class="section blog-wrap" > <div class="col-lg-12 mb-5"> <div class="posts-nav bg-gray p-5 d-lg-flex d-md-flex justify-content-between … -
Inbuilt password validator for password reset Django
In the page where the user reset the password (name="password_reset_confirm"), I want to use inbuild django password validator. But unfortunately, I am not able to bring them up on the page. Currently the two password fields are visible and when I change the password, it is working fine but I need to include the password validation that is offered by Django which will check for these below conditions. Your password can’t be too similar to your other personal information. Your password must contain at least 8 characters. Your password can’t be a commonly used password. Your password can’t be entirely numeric. urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.loginPage, name = "user_login"), path('register/', views.registerPage, name="user_register"), path('registration-success/', views.registerSuccessPage, name="register_success"), path('logout/', views.logoutPage, name = "user_logout"), path('', views.home, name = "home"), path('',include('forum.urls')), path('', include('subscription.urls')), path('', include('core.urls')), #password reset path('reset_password/', auth_views.PasswordResetView.as_view(template_name = "password_reset.html"), name="reset_password"), path('reset_password_sent/',auth_views.PasswordResetDoneView.as_view(template_name = "password_reset_sent.html"),name="password_reset_done"), path('reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name = "password_reset_confirm.html"),name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name = "password_reset_done.html"),name="password_reset_complete"), ] -
Bad request with django and javascript ("POST /user_send_info/ HTTP/1.1" 400 98)
Hi guys I basically wanna get some data using Js and put it in a view in django, but I'm getting bad request ("POST /user_send_info/ HTTP/1.1" 400 98) when I try to get it, the request gets activated when we click a button This my Js section <script> var DateTime = luxon.DateTime; const sendBtns = [...document.getElementsByClassName("send_btn")] sendBtns.forEach(btn => btn.addEventListener('click', () => { const companyName = btn.getAttribute("company-name") const userName = btn.getAttribute("user-name") const fullName = btn.getAttribute("full-name") const email = btn.getAttribute("email") const expireDate = btn.getAttribute("expire-date") const version = btn.getAttribute("version") const code = btn.getAttribute("code") function formatDate(inputDate) { const dt = luxon.DateTime.fromISO(inputDate); if (dt.isValid) { const day = dt.toFormat('dd'); const monthName = dt.toFormat('LLL'); const year = dt.toFormat('yyyy'); return day + '-' + monthName + '-' + year; } return inputDate; } const dateFormatted = formatDate(expireDate); const info = { companyName, userName, fullName, email, dateFormatted, version, code, }; console.log(info) fetch('/user_send_info/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}', }, body: JSON.stringify(info), }) .then(response => response.json()) .then(info => { console.log('Response from Django:', info); }) .catch(error => { console.error('Error to send AJAX request:', error); }); })); </script> This my View in Django from django.http import JsonResponse def email_view(request): if request.method == 'POST' and request.is_ajax(): info … -
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, …