Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django link table row to detail view with buttons to other views
Hey thanks in advance for any help its always much appropriated. So I found this post on here that help do this and it worked great. So i have my table and when you click a row it goes to the right detail view for that row. What i would also like to do is have a column in the table with a button for delete and one for edit for each row. I was able to add the buttons but it looks like the JS code that makes the rows clickable is overriding the buttons. without the JS code the buttons work. Any guidance on what to look up or helpful terms to make the rows clickable and and buttons not be lumped into it. Sorry I've very new to this in general and especially inexperienced in javascript I tested with the rows not clickable (no javascript) and the buttons that are in work and go to the intended view. I also tried moving data-href="{% url 'detail' part.pk %}"the tag in the html the Table tag. this made a single cell clicked as expected (not what i want) but the buttons become clickable again but don't route properly. I … -
Error: The invalid form control is not focusable
I'm encountering an issue with my Django form where I'm getting the following error messages in my browser console: The invalid form control with name=‘content’ is not focusable. An invalid form control is not focusable. I'm not sure what's causing this error or how to resolve it. I've checked my HTML form and Django view, but I can't seem to find any obvious issues. Btw, I'm kind of new to both CKEditor and Django, excuse me for any "dumb" requests - I just couldn't find a fix to this. Here's a snippet of my HTML form: create.html: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Create Post</title> <link rel="stylesheet" href="{% static 'django_ckeditor_5/dist/styles.css' %}"> </head> <body> <div class="container"> <div class="card"> <h1>Create Post</h1> <form action="" method="POST" enctype="multipart/form-data"> <!-- Other fields, removed for simplicity reasons. --> <div class="input"> {{ form.content }} </div> <button type="submit">Create Post</button> </form> </div> </div> <script src="{% static 'django_ckeditor_5/dist/bundle.js' %}"></script> </body> </html> views.py(only the function required for create.html: def createPost(request): if request.user.is_authenticated: if request.method == "POST": form = forms.CreatePostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.slug = slugify(post.title) post.save() messages.success(request, 'Post created successfully.') return redirect('home') else: messages.error(request, 'Error creating post. … -
How can I deploy a Django project with a pickled model in Railway app?
I would like to deploy my Django project on a Railway app, but the server does not find the pickled model. Although I made sure that the file exists in the github repository that I am deploying, Railway app continuously displays this error: from core import views File "/app/core/views.py", line 37, in binary_clf = joblib.load(os.path.abspath('binary_classifier.pkl')) File "/opt/venv/lib/python3.8/site-packages/joblib/numpy_pickle.py", line 650, in load with open(filename, 'rb') as f: FileNotFoundError: [Errno 2] No such file or directory: '/app/binary_classifier.pkl' The thing is, I don't have any static files except for this pickled ML model. But, I tried including the pickled model in a 'static' folder like it was described here, in which case I got this error: from core import views File "/app/core/views.py", line 37, in binary_clf = joblib.load("static/binary_classifier.pkl") File "/opt/venv/lib/python3.8/site-packages/joblib/numpy_pickle.py", line 650, in load with open(filename, 'rb') as f: FileNotFoundError: [Errno 2] No such file or directory: 'static/binary_classifier.pkl' How are we supposed to deploy Django apps when we have pickled files in it? -
Operational Error in Django: Migrating a Python Web Application to a mariadb database
I am trying to connect a mariadb database that I created in a Linux VM and have my python web application migrate the files over. When I use the python manage.py migrate command, I come across this error: django.db.utils.OperationalError: (2002, "Can't connect to server on '127.0.0.1' (36)") When connecting to the database in my terminal, I end up with this error: mysql -h '127.0.0.1' -P maxdj2k polls_db ERROR 2002 (HY000): Can't connect to server on '127.0.0.1' (36) I'm trying to connect via unix_socket, and have already routed the file to the correct path in my my.cnf file. (/tmp/mysql.sock) is not correct and I'm not entirely sure why it designates that as the path outright. Here is my DATABASES section in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'NAME': 'polls_db', 'USER': 'maxdj2k', 'PASSWORD': 'M24i21F27*', } } I've also included an options parameter under 'PASSWORD' to specify where the actual path for my socket file is. Here is my my.cnf file In linux: # # This group is read both both by the client and the server # use it for options that affect everything # [client-server] socket=/var/lib/mysql/mysql.sock port=3306 # # include all files from the config directory # … -
cannot get token and store it is local storage
I want to while logging user to send post request to http://127.0.0.1:8000/auth/token/login to get auth user token, store it i local storage and then log in user i need this token in local storage for sending post request and getting api response back in my vue cuz now it hardcoded <template> <div> <div v-if="question">{{ question }}</div> <div v-else>Loading...</div> </div> </template> <script> import axios from 'axios'; export default { name: 'QuestionView', props: { slug: { type: String, required: true, }, }, data() { return { question: null }; }, methods: { async getQuestionData() { const endpoint = `http://localhost:8000/api/v1/questions/${this.slug}`; try { const response = await axios.get(endpoint, { headers: { 'Authorization': 'token (here is my token) ' }s }); this.question = response.data; // Assuming your API response is an object containing question information } catch(error) { console.log(error.response); alert(error.response.statusText); } } }, created() { this.getQuestionData(); } } </script> this login.html logging user but doesn't save token {% extends "auth_layout.html" %} {% load widget_tweaks %} <script> async function loginUser(event) { event.preventDefault(); var username = document.getElementById("username").value; var password = document.getElementById("password").value; console.log('a') try { console.log("s") const response = await fetch("http://127.0.0.1:8000/auth/token/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: username, password: password }) }); if … -
I created a Babylon with meshes loaded in a X Django app template, now I need to rotate it by clicking buttons located a dash-board on a y Django app
I'm using a Babylon in a Django project, created a app template that I have few meshes loaded and I did set buttons to rotate the meshes using addEventListener, it are working well when the UI buttons is located in the same HTML template where the canvas is loaded, APP X. My main goal is to have the UI buttons located in a template that will be a dash-board created on a different APP, APP Y on my Django project. When I place the UI buttons in the Y APP (dash-board template) I get the error: Uncaught TypeError: Cannot read properties of undefined (reading 'trackUbosInFrame') at new e (uniformBuffer.ts:256:36) at t.createSceneUniformBuffer (scene.ts:2405:26) at Ar.createSceneUniformBuffer (engine.multiview.ts:203:12) at t._createUbo (scene.ts:1933:41) at new t (scene.ts:1690:14) at HTMLDocument. (jackpot.js?v=:7:17). My JS rotation setup located in my Django JS file inside X APP: javascript function createRotationLogic(mesh, axis, speed) { var rotationAxis; switch (axis) { case "X": rotationAxis = BABYLON.Axis.X; break; case "Y": rotationAxis = BABYLON.Axis.Y; break; case "Z": rotationAxis = BABYLON.Axis.Z; break; default: rotationAxis = BABYLON.Axis.Y; } return function () { scene.unregisterBeforeRender(mesh); scene.registerBeforeRender(function () { mesh.rotate(rotationAxis, speed, BABYLON.Space.LOCAL); }); setTimeout(function () { scene.unregisterBeforeRender(mesh); }, 30000); // Stop after 30 seconds }; } // Function to … -
Javascript request to Python Django not found
I am new to Django and Javascript. Now totally stuck with this error, probably a really small thing, but I can not figure out what can be the problem. I would like to delete a document through my form using Javascript and send it to my Django backend through a request. At the terminal I get this error message: "Not Found: /delete_document/7/ [23/Feb/2024 13:26:53] "DELETE /delete_document/7/ HTTP/1.1" 404 2371" The request color is yellow and it happens as I see, it just can not find my view function. views.py @require_http_methods(['DELETE']) def delete_document(request, document_id): document = get_object_or_404(Document, pk=document_id) document.delete() return JsonResponse({'message': 'Document deleted successfully'}, status=204) urls.py from django.urls import path from . import views # Define namespace app_name = 'advice' urlpatterns = [ ... path('delete_document/<int:document_id>/', views.delete_document, name='delete_document'), ] index.html relevant parts <form id="documentForm" action="" method="post" data-base-action="{% url 'advice:gpt_base' %}"> {% csrf_token %} <input type="hidden" name="firstQuestion" value="True"> <select id="documentSelect" class="form-select" aria-label="Select form"> <option selected>Select a file</option> {% for document in documents %} <option value="{{ document.id }}">{{ document.title }}: {{ document.uploaded_file.url }}</option> {% endfor %} </select> <button type="button" class="btn btn-danger" id="deleteButton">Delete</button> <br> <button type="submit" class="btn btn-primary">Submit</button> </form> <script> document.getElementById('deleteButton').addEventListener('click', function() { var selectedDocumentId = document.getElementById('documentSelect').value; if (selectedDocumentId === 'Select a file') { alert('Please … -
Slow response from Django Rest Framework with annotated queryset
I am using Django Rest Framework and simply trying to filter out objects which have more than 0 related items but as soon as I add in a filter to my annotation that includes a datetime, the response time goes from milliseconds to 90 seconds or so. Here is the code that takes ages:- class EventVenueViewSet(viewsets.ReadOnlyModelViewSet): queryset = EventVenue.objects.annotate( num_slots=models.Count( "eventblock__eventslot", filter=Q(eventblock__status='active') & Q( eventblock__eventslot__start_time__gt=timezone.now() + timedelta(days=2) ) ) ).filter(num_slots__gt=0) If I remove the filter that includes the DateTimeField (start_time)... class EventVenueViewSet(viewsets.ReadOnlyModelViewSet): queryset = EventVenue.objects.annotate( num_slots=models.Count( "eventblock__eventslot", filter=Q(eventblock__status='active') ) ).filter(num_slots__gt=0) it is very fast. But the presence of that datetime filter slows it down to the point of being useless. It's nothing to do with db lookups - it's doing 8 of those so that's fine. The SQL query looks fine and the results are correct - it's just taking soooooo long! Any ideas? -
Could not translate host name "db" to address: Name or service not known
I'm using Django + Docker and when building the image of one of my projects I'm facing problems when running the command: docker-compose run web python manage.py makemigrations error: root@debian:/home/suportenpd1/Documentos/setorT# docker-compose run web python manage.py makemigrations [+] Creating 1/0 ✔ Container setort-db-1 Created 0.0s [+] Running 1/1 ✔ Container setort-db-1 Started 1.1s /usr/local/lib/python3.12/site-packages/django/core/management/commands/makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "db" to address: Name or service not known warnings.warn( No changes detected docker-compose.yml: services: db: image: postgres:15.6 volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=setorT - POSTGRES_USER=setorT - POSTGRES_PASSWORD=setorT@2024$ ports: - "5432:5432" web: build: . command: ["./wait-for-it.sh", "db:5432", "--", "python", "manage.py", "runserver", "0.0.0.0:8000"] volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=setorT - POSTGRES_USER=setorT - POSTGRES_PASSWORD=setorT@2024$ depends_on: - db setting.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, } } -
Got "No Books matches the given query" error even though the object exist on Django
I got this problem where Django return "No Books matches the given query", even though the object exist in database. For context, I want to create an update page without relying the use of URL. First, here is my model : User = get_user_model() class Books(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=50) author = models.CharField( max_length=40, ) author_nationality = models.CharField(max_length=20, default='Japanese') author_medsos = models.CharField(max_length=30, default='None') book_type = models.CharField( max_length=10, null=True, choices=BOOKS_TYPES ) tl_type = models.CharField( max_length=20, null=True, choices=TRANSLATION_BY ) series_status = models.CharField( max_length=20, choices=SERIES_STATUS, default=ONG ) source = models.CharField(max_length=100) # source can refer to downloage page, example = https://www.justlightnovels.com/2023/03/hollow-regalia/ reading_status = models.CharField( max_length=20, choices=READING_STATUS, default=TOR ) current_progress = models.CharField( # For tracking how many chapter have been read max_length=30, null=True ) cover = models.FileField(upload_to='cover/', default='cover/default.png') genre = models.CharField(max_length=40, null=True) class Review(models.Model): books = models.ForeignKey('Books', on_delete=models.CASCADE, null=True) volume = models.IntegerField() review = models.TextField() Before the user get to the update page, they first have to visit /library page, {% for book in user_books %} <div class='lib-item'> <form method='POST' action="{% url 'core:update_library' %}"> {% csrf_token %} <input type='hidden' name='book_id' value='{{ book.id }}'> <button type='submit'> <img src={{ book.cover.url }} width='185'> <span> {{ book.title }} </span> </button> </form> </div> {% endfor … -
In Django Rest Framework how to make a function base view roll back every change made if somethings fails
I have a api endpoint that the user will send a key pair of file_field: File in the multipart content type. The function need to update every document and create a history about the change. Then It should complete the session that the user used to do this change. If a document couldn't be updated or a historic couldn't be created all the operations and changes should roll back how to archive this. This is my current function base view: @transaction.atomic @api_view(['POST']) @parser_classes([JSONParser, MultiPartParser]) @permission_classes([HasSpecialSessionPermission]) def update_documents(request): user = request.user special_session = SpecialSessionConfiguration.objects.filter(user=user, completed=False).first() lot = DefaultLotModel.objects.filter(user=user, call__active=True).first() for key, uploaded_file in request.FILES.items(): try: validate_file_size(uploaded_file) if key != 'financial_form' and key != 'power_point': validate_file_extension(uploaded_file) except ValidationError as e: return Response({'message': str(e)}, status=status.HTTP_400_BAD_REQUEST) if special_session.special_session_fields.filter( field_name=get_field_number(SPECIAL_SESSION_FIELD, key)).exists(): if hasattr(lot, key): current_file = getattr(lot, key) if current_file: setattr(lot, key, uploaded_file) LotDocumentHistory.objects.create( lot=lot, old_file=current_file, field_name=key, ) setattr(lot, key, uploaded_file) lot.save() else: for child_field in ['first_lots', 'second_lots', 'third_lots']: child_lot = getattr(lot, child_field, None) if child_lot and hasattr(child_lot, key): current_file = getattr(child_lot, key) if current_file: LotDocumentHistory.objects.create( lot=lot, old_file=current_file, field_name=key, ) setattr(child_lot, key, uploaded_file) child_lot.save() elif special_session.extra_files: try: data = {'name': key, 'file': uploaded_file, 'lot': lot.pk} serializer = ExtraFileSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() except ValidationError as ve: error_dict … -
Difficulty Using gettext_lazy in Django 4 Settings with django-stubs, Resulting in Import Cycle and mypy Type Inference Error
Problem: Mypy Error: The mypy error encountered is as follows: error:Import cycle from Django settings module prevents type inference for 'LANGUAGES' [misc] I'm encountering challenges with the usage of gettext_lazy in Django 4 settings while utilizing django-stubs. The recent update in Django 4 brought changes to the typing of gettext_lazy, where the old return type was str, and the new type is _StrPromise. The issue arises from the fact that _StrPromise is defined in "django-stubs/utils/functional.pyi," and within this file, there is also an import of django.db.model which imports settings. This creates a circular import. current module-version: typing mypy = "1.7" django-stubs = "4.2.7" Django dependencies Django = "4.2.10" Seeking advice on a cleaner and more sustainable solution to the circular import issue and mypy error in the context of Django 4 settings with the updated gettext_lazy typing. Any insights or alternative approaches would be greatly appreciated. possible Solutions: Several solutions have been considered, but none of them are ideal: Disable Mypy Typing for Settings: Disabling Mypy typing for settings is a workaround, but it might compromise the benefits of static typing. Remove gettext_lazy from Settings: Another option is to remove gettext_lazy from settings. However, this contradicts the current recommendations in … -
Django - CSRF Failed: CSRF cookie not set
I want to create a API that has login / logout / signup / edit etc, but when I try it in Postman i get the error: CSRF Failed: CSRF cookie not set I've noticed that if the user is not logged in, The API works fine but after the login I get the CSRF error when using any url from it ( /logout/, /login/ etc) views.py `@csrf_exempt @api_view(['POST']) def login_user(request): if request.user.is_authenticated: return JsonResponse({"detail": "User is logged in!"}) body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) nickname = body['nickname'] password = body['password'] user = authenticate(nickname=nickname, password=password) if user is not None: login(request, user) logout(request) return JsonResponse({"response": "Login success!"}) else: return JsonResponse({"error": "Nickname or Password are incorrect!"})` settings.py `MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]` I've seen that I should get a CSRF token in the cookies section in Postman, but the only thing i get is a sessionId -
why this error coming actually there is issue related to migrations so i tried to delete the all migrations files then
return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.ProgrammingError: relation "auth_group" does not exist why it is showing like that can you explain how actually migrations works i am expecting to schema to migrate in database -
Circular Import - Django
I can't see where the circular import is django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'Reciept.urls' from 'Reciept\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import project level urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('PPMS/', include('PPMS.urls')), path('Dispute/',include('Dispute.urls')), path('Reciept/', include('Reciept.urls')) ] urls.py from django.urls import path from .views import Disputeindex app_name='Dispute' urlpatterns = [ path('',Disputeindex, name='Disputeindex') ] View.py from django.shortcuts import render def Recipetindex(request): return render(request, 'Reciept/index.html') -
Why does Django order by column number instead of column name?
I have this Django ORM code: queryset.filter(filters).annotate(rank=SearchRank(vectors, search_query)).order_by('-rank').distinct() and Django transforms this code into that sql: SELECT DISTINCT "model_1"."id", ... ... ... ts_rank( "model_2"."search_vector", phraseto_tsquery(query) ) AS "rank" FROM "model_1" INNER JOIN "model_2" ON ( "model_1"."id" = "model_2"."case_id" ) WHERE ( "model_2"."search_vector" @@ ( phraseto_tsquery(query) ) ) ORDER BY 41 ASC I cant understand why Django use 41(its a number of annotated rank column) instead of column name and i cant find any Django docs that describe this logic. Django version: 5.0.2 -
Celery Task Fails with "Object Does Not Exist" Error Despite Using Auto-Commit in Django
In my Django application, I've encountered a rare issue where a Celery task, invoked via apply_async immediately after creating an object in a model's save method, failed because it could not find the newly created object. This issue has occurred only once, making it particularly puzzling given Django's auto-commit mode, which should commit the new object to the database immediately. Below is a simplified version of the code where the issue appeared: from django.db import models from myapp.tasks import process_new_object class MyModel(models.Model): .... class AnotherModel(models.Model): .... def save(self, *args, **kwargs): new_obj = MyModel.objects.create(name="Newly Created Object") process_new_object.apply_async(args=[new_obj.pk], countdown=5) return super().save(*args, **kwargs) @shared_task def process_new_object(obj_id): try: obj = MyModel.objects.get(pk=obj_id) ... except MyModel.DoesNotExist: pass what might be potential causes for the Celery task to sometimes fail to find the newly created object, despite the delay and Django's auto-commit? -
Docker container restarting without producing logs
I'm encountering an issue with a Docker container where it keeps restarting without producing any logs. Here are the details of my setup: I have a Docker Compose configuration with two services: profiles and postgres. The profiles service is built from a custom Dockerfile and runs a Python application. The postgres service uses the official PostgreSQL Docker image. Both services are defined in the same docker-compose.yml file. The profiles service container (profile-profiles-1) keeps restarting, but when I try to view its logs using docker logs profile-profiles-1, there is no output. Here is my docker-compose.yml: x-variables: &variables ENV_STAGE: local services: profiles: build: context: . dockerfile: ./compose/dev/web/Dockerfile volumes: - ./web/:/usr/src/web/ ports: - "8000:8000" environment: <<: *variables env_file: - compose/dev/env/.env - compose/dev/env/.db.env - compose/dev/env/.data.env depends_on: - postgres restart: unless-stopped postgres: image: postgres:latest restart: always volumes: # - postgres-data:/var/lib/postgresql/data # - compose/dev/db/pg.conf:/etc/postgresql/postgresql.conf - ./compose/dev/db/pg.conf:/etc/postgresql/postgresql.conf environment: - POSTGRES_USER=test - POSTGRES_PASSWORD=password - POSTGRES_DB=test - PGDATA=/var/lib/postgresql/data ports: - 5432:5432 # command: # - config_file=/etc/postgresql/postgresql.conf command: postgres -c config_file=/etc/postgresql/postgresql.conf env_file: - compose/dev/env/.db.env volumes: postgres-data: This is my Dockerfile for the application: # pull official base image FROM python:3.9-alpine ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ LANG=C.UTF-8 \ HOME=/usr/src/web WORKDIR $HOME ARG GID=1000 ARG UID=1000 ARG USER=ubuntu # install dependencies RUN … -
How to set dict key as dynamic field name to add value m2m fields in Django
I want to set the m2m field name from the dictionary key dynamically so that I don't have to type each field name separately. Any help would be much appreciated. instance = ProductAttributes.objects.create(device_type=1, manufacturer=2, created_by=request.user) device_dict = { 'watch_series': WatchSeries.objects.get(series=mergedict['watch_series']), 'watch_size': WatchSize.objects.get(size=mergedict['watch_size']), 'color': Color.objects.get(id=mergedict['color']), 'band_color': BandColor.objects.get(color=mergedict['band_color']), 'watch_connectivity': 1 if mergedict['is_gps'] == True else 2 } This is how I'm trying to add m2m field name after instance for key, val in device_dict.items(): instance._meta.get_field(key).add(val) I'm getting this error: AttributeError: 'ManyToManyField' object has no attribute 'add' -
How to create Tree Survey in Django?
I need help You need to do a tree survey in jang Type : Question: Who do you work for? Answer options : Programmer, Welder If the user answers as a Programmer, they are asked questions about this profession If a welder answers, he is asked questions about this profession Well, and so on into the depths That is, the user's answers affect the next question But you also need to create a custom admin panel to add, edit and establish links between these issues I just can't figure out how to optimally configure the models so that the tree survey is normally implemented. Specifically, I do not understand how to store this connection, how to store it correctly and conveniently in models, and how to implement them so that quickly, beautifully and simply you can specify these links between questions and answers in the admin panel -
How can I automatically assign the current user as the author when creating a post?
How can I automatically assign the current user as the author when creating a post? forms: from django import forms from publication.models import Userpublication class PostForm(forms.ModelForm): content = forms.CharField(label='',widget=forms.Textarea(attrs={'class': 'content_toggle app-textarea', 'utofocus': 'true', 'maxlength': '250', 'placeholder': 'hello', 'required': True})) class Meta: model = Userpublication fields = ['content', 'author'] labels = { 'Content': False, } views: def create_post(request): if request.method == 'POST': form = PostForm(request.POST, initial={'author': request.user}) if form.is_valid(): form.save() return redirect('home') else: form = PostForm(initial={'author': request.user}) post_lists = Userpublication.objects.all() context = { 'form': form, 'post_lists': post_lists, } return render(request, 'twippie/home.html', context) enter image description here This is how it works. But as soon as I remove fields 'author' from the form, but 'content' remains, the following error appears: File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages django\db\backends\sqlite3\base.py", line 328, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.IntegrityError: NOT NULL constraint failed: publication_userpubl ication.author_id the browser shows this error: IntegrityError at /feed/ NOT NULL constraint failed: publication_userpublication.author_id What could I have missed or overlooked? model if needed: from django.db import models from autoslug import AutoSlugField from django.urls import reverse from django.contrib.auth.models import User from django.conf import settings class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_published=1).order_by('-time_create') class Userpublication(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = AutoSlugField(max_length=255, unique=True, populate_from='content') content = models.TextField('', blank=True) … -
I am unable to use Django Filter for Related Foreignkey in Django model
I am unable to filter reverse Foreign key field in my filter. Here is My Main Model: class VendorService(models.Model): """ Class for creating vendor services table models. """ vendor_id = models.ForeignKey(CustomUser, null=False, blank=False, on_delete=models.CASCADE) service_id = models.ForeignKey(Service, null=False, blank=False, on_delete=models.CASCADE) business_name = models.TextField(null=True, blank=False) business_image = models.URLField(max_length=500, null=True, blank=False) working_since = models.TextField(null=True, blank=False) ... And Here is my second Model: class ServiceSubTypeDetail(models.Model): ''' Additional Service Details ''' title = models.CharField(max_length=255, null=True, blank=True) service_subtype = models.CharField(max_length=255, null=True, blank=True) service = models.ForeignKey(VendorService, related_name='subtypes', on_delete=models.CASCADE, null=True, blank=True) actual_price = models.FloatField(null=True, blank=True) ... My second model uses First Model as foreignkey And Here is my Filter Class using django-filter library: class ServiceFilter(filters.FilterSet): service_type = filters.CharFilter(field_name="service_id__service_type", lookup_expr='icontains') city = filters.CharFilter(field_name="city", lookup_expr='icontains') price = filters.RangeFilter(field_name="vendorpricing__discounted_price") subscription = filters.CharFilter(field_name="vendorplan__subscription_type", lookup_expr='iexact') property_type = filters.CharFilter(field_name="subtypes__title", lookup_expr='icontains') def __init__(self, *args, **kwargs): super(ServiceFilter, self).__init__(*args, **kwargs) # Dynamically add the price range filter based on the service_type service_type = self.data.get('service_type', None) if service_type == 'Venues': self.filters['price'] = filters.RangeFilter(field_name="venue_discounted_price_per_event") else: self.filters['price'] = filters.RangeFilter(field_name="vendorpricing__discounted_price") class Meta: model = VendorService fields = ['service_id__service_type', 'city', "vendorpricing__discounted_price", "venue_discounted_price_per_event", "subtypes__title"] all other filters are working properly, but property_type dosnt work at all. I tried using method as well. please help..!! -
Change style for filteredselectmultiple widget tooltip text
I have used help help-tooltip help-icon in that I want add bootstrap tooltip styles. But not able to do? For reference I have attached screenshot. Provide solution according to that.in following image that question mark shows tooltip text and i want add bootstrap tooltip style in that text . enter image description here Add bootstrap tooltip style for tooltip -
Django Media files is not displaying when debug=false on production in Render
I currently have two kind of files static files and media files.The static files contain my css,js and other static content. The media files contain stuff that the user uploads.The static folder is right next to the media folder.Now on my deployed machine. If I set the DEBUG = False my static files are presented just fine however my media content is never displayed `This my settings.py code were debug=false and included the code for the static but my media files is not displaying in the render hosting platform .I want to display my media files on production server when debug=False ` DEBUG = False ALLOWED_HOSTS = ["*"] This my static code but i get static files and it is displaying in the production .But the media files are not displaying in the production server is there any way to solve this problem STATIC_URL = '/static/' STATICFILES_DIRS=[os.path.join(BASE_DIR,'static')] STATIC_ROOT=os.path.join(BASE_DIR,'assets') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") Im using Render hosting platform for the deployment of the application -
A p2p secure chat application need more ressources to establish the work
I want to do this so called p2p chat app project, and I need some clear guidance and ressources where I can find some good p2p documentation or courses so I can digest this notion, I'm not so familiar woth it even though I have some basic knowledge about it I hope u suggest some great ressources where I can find a p2p based book or documentation