Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check the details are correct or not without rendering the page in django?
I have created a registration form using django framework and in the phone number content how can I check the number is only equal to 10 digits without rendering the page, because when i render the page if the phone number condition is wrong whole input's will be deleted and return the page how can i handle that without deleting the data?? i have explained as above -
Prettier - How to format HTML files as expected, in a Django project
I have difficulties in formatting HTML files as expected. Here are some of them: (1) Expectation (before being saved): After being saved and formatted (not as expected): (2) Expectation (before being saved): After being saved and formatted (not as expected) : (3) Expectation (before being saved): After being saved and formatted (not as expected): My .prettierrc is as follow: { "singleQuote": true, "printWidth": 80, "useTabs": true, "overrides": [ { "files": ["**/*.html"], "options": { "printWidth": 150 } } ] } I feel like the expected ones make the file more readable. Am I missing some configurations in .prettierrc? Thank you -
Django 4.1 Static Files
I recently migrated from Django 3.8 to 4.1 without much issue, but since then, when I have DEBUG=True in my development environment, changes to Static Files are not reflected when refreshing the page, I instead have to reboot my dev environment. All other changes, including template changes and view changes are working as expected, just not static file changes. To fix the template changes issue I updated my templates variable from: { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] to: default_loaders = [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ] cached_loaders = [("django.template.loaders.cached.Loader", default_loaders)] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates'], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'loaders': default_loaders if DEBUG else cached_loaders, }, }, ] Which worked perfectly, however still, changes to my static files are not being served. I have tried disabling my browser cache with no luck. I am using Docker to run the dev environment with Docker Compose. Let me know if you need any other information, wasn't 100% sure what to provide as I have no idea what may be causing it. -
displaying image from sqlite in django
I have a model that has a field of Image profile_picture = models.ImageField(upload_to='clothes_images', null=True, blank=True). I have a function that returns the image URL def image_url(self): if self.profile_picture: return self.profile_picture.url return None but when I display in my template using this code <img src="{{cloth.image_url}}"> I get this error Not Found: /media/clothes_images/1_fSqDIIb.png my image name is 1.png but it changes when I store that and not find that. I want to display each image that stores in my local system. -
Django Schema Reverse Related Objects
I have the following two Django models: class Participant(models.Model): name = models.TextField() sport = models.TextField() bookmaker = models.ForeignKey(Bookmaker, on_delete=models.CASCADE) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ("name", "bookmaker", "sport") def __str__(self) -> str: return f"{self.name} ({self.sport}) | {self.bookmaker.name}" class BookmakerParticipant(models.Model): sharp_participant = models.OneToOneField( Participant, on_delete=models.CASCADE, primary_key=True, related_name="sharp_participant_match" ) soft_participants = models.ManyToManyField( Participant, related_name="soft_participant_matches" ) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) In my schema definition I'd like to access all the BookmakerParticipant objects where the Participant is in soft_participants from the Participants perspective. Thus, I created the following schema: class UnmatchedParticipantSchema(ModelSchema): bookmaker: BookmakerSchema soft_participant_matches: BookmakerParticipantSchema class Meta: model = Participant fields = [ "name", "sport", "bookmaker", "soft_participant_matches" ] However, this creates the following error in Django ninja.errors.ConfigError: DjangoField(s) {'soft_participant_matches'} are not in model <class 'core.models.Participant'>. How do I resolve this? -
Why i'm getting 403 error while creating a docker image?
Dockerfile: FROM python:3.19-alpine WORKDIR /app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PATH="/PY/BIN:$PATH" RUN pip install --upgrade pip COPY ./req.txt /app/req.txt COPY . /app RUN pip install -r req.txt docker-compose.yml: version: '3.8' services: django: container_name: django_celery_project build: context: ./ dockerfile: Dockerfile command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - "8000:8000" environment: - ALLOWED_HOSTS=localhost,127.0.0.1 - DEBUG=True - SECRET_KEY=*********** command : docker-compose up -d --build result : => [django internal] load .dockerignore 0.0s => => transferring context: 87B 0.0s => [django internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 270B 0.0s => ERROR [django internal] load metadata for docker.io/library/python:3.19-alpine 10.7s => [django auth] library/python:pull token for registry-1.docker.io 0.0s error : failed to solve: python:3.19-alpine: failed to authorize: failed to fetch oauth token: unexpected status from POST request to https://auth.docker.io/token: 403 Forbidden My IP address without a VPN is: 93.115.225.147 My IP address with VPN is: 213.142.149.230 -
Serving static files with presigned URLs
I have a Django application hosted in AWS Lightstail and its static and media files hosted in a S3 bucket. The client is asking me to serve ALL the files (static and media) through AWS's presigned URLs. To my knowledge, presigned URLs are more suitable for media or single files rather than all the website's static files, since every time someone access the website, a new URL is generated for each static file, causing loading delays and misusage of the URLs' expiration time. I suggested to set up CloudFront instead. My question: Is the client's request reasonable? And if so, is there a way to serve these static files in a way that the presigned URLs are not created with every new access to the website? -
Display Image related to a Foreign Key
I have scoured the Internet, ChatGPT, StackOverflow, etc, and cannot find out how to make an image from my AWS S3 bucket (from a foreign key) appear in my template. The images work perfectly fine when they aren't connected via a foreign key and I am showing just students and their images. views.py #@login_required @user_passes_test(lambda u: u.groups.filter(name='teacher').exists()) def hallpasses(request): students = HallPass.objects.filter(dateissued__date = todaysdate2.date ) allstudents = Student.objects.all() context={'students':students, 'todaysdate2':todaysdate2, 'allstudents':allstudents, } return render(request, 'pass.html',context) models.py #HallPass model class HallPass(models.Model): DESTINATIONS=( ('Activities Office', 'Activities Office'), ('Alumni Office', 'Alumni Office'), ('Cafeteria', 'Cafeteria'), ('Chelsea Center', 'Chelsea Center'), ('Counseling Center', 'Counseling Center'), ('Cr. Counselor', 'Cr. Counselor'), ('Library', 'Library'), ('Nurse', 'Nurse'), ('Office 124', 'Office 124'), ('Office 157', 'Office 157'), ('Office 210', 'Office 210'), ('Office 308', 'Office 308'), ('Other', 'Other'), ('Locker', 'Locker'), ('Main Office', 'Main Office'), ('Teachers Room', 'Teachers Room'), ('Restroom', 'Restroom'), ('Water', 'Water'), ('WGHS Academy', 'WGHS Academy'), ('Art Department','Art Department'), ('Business Department','Business Department'), ('English Department','English Department'), ('FACS Department','FACS Department'), ('Industrial Tech Department','Industrial Tech Department'), ('Math Department','Math Department'), ('Music Department','Music Department'), ('Makerspace','Makerspace'), ('PE Department','PE Department'), ('Science Department','Science Department'), ('Social Studies Department','Social Studies Department'), ('SSD Department','SSD Department'), ('Theater Arts Department','Theater Arts Department'), ('World Languages','World Languages'), ) student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="images") dateissued = models.DateTimeField(null=False,blank=False) teacherissuing = … -
How to fix importerror or Pythonanywhere deployment with Python upgrade?
I am using Python 3.8 on my mac and developing an app for more then two years. I am hosting this app on PythonAnywhere because I'm using Sqlite3. Now PA sent me an email that I need to upgrade the system image from Python 3.8 to 3.10. I never done this before so I'm registered a free account and deployed the exactly same app to test the process. I made a new project, virtualenv and installed Python 3.10 and Django 5.0 (tried 3.1 too - this is the version on my Mac). I did all the setting ans setted the wsgi too like many times before in other projects. When I installed all the apps and try to run the site I get this very long error traceback: 2023-12-20 18:37:37,746: Error running WSGI application 2023-12-20 18:37:38,100: ImportError: cannot import name 'SuccessURLAllowedHostsMixin' from 'django.contrib.auth.views' (/home/ruszakmikloseu/.virtualenvs/mpa-virtualenv/lib/python3.10/site-packages/django/contrib/auth/views.py) 2023-12-20 18:37:38,100: File "/home/ruszakmikloseu/.virtualenvs/mpa-virtualenv/lib/python3.10/site-packages/django/core/handlers/wsgi.py", line 124, in __call__ 2023-12-20 18:37:38,100: response = self.get_response(request) 2023-12-20 18:37:38,101: 2023-12-20 18:37:38,101: File "/home/ruszakmikloseu/.virtualenvs/mpa-virtualenv/lib/python3.10/site-packages/django/core/handlers/base.py", line 140, in get_response 2023-12-20 18:37:38,101: response = self._middleware_chain(request) 2023-12-20 18:37:38,101: 2023-12-20 18:37:38,101: File "/home/ruszakmikloseu/.virtualenvs/mpa-virtualenv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 57, in inner 2023-12-20 18:37:38,102: response = response_for_exception(request, exc) 2023-12-20 18:37:38,102: 2023-12-20 18:37:38,102: File "/home/ruszakmikloseu/.virtualenvs/mpa-virtualenv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 140, in response_for_exception 2023-12-20 18:37:38,102: … -
React Django app not updating component after change
I was working on a react js app with django backend. I made some changes to my search page component but my browser is still rendering the old search page. Here is the code for my search page import React, { useState, useEffect } from "react"; import TextField from "@material-ui/core/TextField"; import Button from "@material-ui/core/Button"; import axios from 'axios'; const SearchPage = () => { const [searchTerm, setSearchTerm] = useState(''); const [searchResults, setSearchResults] = useState(null); const [recentSearches, setRecentSearches] = useState([]); useEffect(() => { const storedSearches = localStorage.getItem('recentSearches'); if (storedSearches) { const parsedSearches = JSON.parse(storedSearches); console.log("Loaded searches:", parsedSearches); setRecentSearches(parsedSearches); } else { console.log("No recent searches found in localStorage"); } }, []); const handleSearch = async () => { try { const response = await axios.get('/backend/search', { headers: { 'Cache-Control': 'no-cache', }, params: { searchTerm: searchTerm, start: 0, }, }); setSearchResults(response.data); if (searchTerm.trim() !== '') { const updatedSearches = [searchTerm, ...recentSearches.filter(search => search !== searchTerm).slice(0, 4)]; setRecentSearches(updatedSearches); localStorage.setItem('recentSearches', JSON.stringify(updatedSearches)); } } catch (error) { console.error('Error fetching data: ', error); } }; return ( <div> <div style={{ margin: "20px" }}> <TextField label="Enter search term" variant="standard" fullWidth onChange={(e) => setSearchTerm(e.target.value)} /> </div> <div style={{ margin: "20px" }}> <h3>Recent Searches:</h3> <ul> {recentSearches.map((search, index) => ( <li … -
I'm unable to create superuser in Django
I'm unable to create a user profile in terminal after I have created Django environment by typing py manage.py createsuperuser it's unfortunately showing *** exe: can't open file 'C:\User\USER\manage.py'[Errno 2] No such file or directly *** I don't know what to do, I'm just keep trying and trying if it would work, I'm just keeping rolling a dice with no face that why I'm here, I'm expecting a best solution that will relieve the tie that tight my neck -
On media screen, swiping over the home-slider doesn't move
While checking mobile screen, found out that I have to swipe on top of the navbar to swipe through the homepage from top to bottom. If I swipe over the home-slider, it doesn't do anything since on media screen the home-slider is in full height and I am using a pre made template for python django project <section class="home-slider js-fullheight owl-carousel bg-white"> <div class="slider-item js-fullheight"> <div class="overlay"></div> <div class="container"> <div class="row d-md-flex no-gutters slider-text js-fullheight align-items-center justify-content-end" data-scrollax-parent="true"> <div class="one-third order-md-last"> <img class="js-fullheight" src="/static/images/coverpic1.jpeg" alt="background"> <h3 class="vr">Builders & Developers</h3> </div> <div class="one-forth d-flex js-fullheight align-items-center ftco-animate" data-scrollax=" properties: { translateY: '70%' }"> <div class="text"> <h1 class="mb-4" style="font-family: 'Lobster Two', sans-serif;">We don't just build,<br> we build legacies</h1> <p style="width: 50%; text-align: justify; font-family: 'Afacad', sans-serif;">At Maskn, we transcend construction, building legacies that stand as timeless testaments to our commitment to excellence.</p> <p><a href="/project" class="btn btn-primary px-4 py-3 mt-3">View our works</a></p> </div> </div> </div> </div> </div> This is my code for the home slider I tried to reduce the height of the slider, but it reduces the aesthetic of the page. -
Django & DRF: trying to find a way to reuse code for user registration for web and REST api
I have a working Django based web experience that has a CustomUser (AbstractUser) model to remove username and require email as default. I implemented a "register" function within views.py that set is_email_verified to FALSE (which is only set to TRUE by the email verification component). Now, I am creating REST services that could be used by a mobile app. I find the logic for the register function within api/views.py to be very similar to the register function within the views.py supporting the web experience. While I can extract the common code into a common function (and call it from both web and api register functions), is it a bad practice to instead update the web register function as follows (and call it from the POST function within the api/views): web views.py: @api_view(['POST']) @permission_classes([AllowAny]) @csrf_exempt def register(request): if request.method == 'POST': if request.content_type == 'application/json': # registration via API call data = json.loads(request.body) user_form = UserRegistrationForm(data) else: # registration via web user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.is_email_verified = False new_user.save() Profile.objects.create(user=new_user) send_email_verification_email(request, new_user) if request.content_type == 'application/json': # API response with token token, created = Token.objects.get_or_create(user=new_user) if created: return Response({'message': _('User registered successfully'), \ 'token': token.key, 'created': … -
django_filters and drf_yasg is not compatible
I am developing a project where I am using django_filters and there are some views where I have filters and apparently I have problems because of that. This is the message "UserWarning: <class 'apps.tenant_apps.orders.api.views.TotalProductsByOrderStateAPIView'> is not compatible with schema generation" and comes from django filters. I am following the documentation to the letter but I see no support for this warning. What should I do? django_filters docs: https://django-filter.readthedocs.io/en/stable/index.html drf_yasg docs: https://drf-yasg.readthedocs.io/en/stable/ class ProductByCategoriesListView(TenantListApiViewMixin): # 2. Listar productos por categoría o categorías # http://example.localhost:8000/api/products/list/category/?categories=Electr%C3%B3nica,Ropa%20y%20Accesorios,Ropa,Calzado,Muebles%20y%20Decoraci%C3%B3n serializer_class = ProductByCategorySerializer def get_queryset(self): categories = self.request.query_params.get('categories', '').split(',') queryset = [] for category in categories: # Utiliza Q objects para construir las condiciones OR q_objects = Q() q_objects |= Q( channelproduct_product__productcategory_channelproduct__channel_category__category__icontains=category) q_objects |= Q( channelproduct_product__productcategory_channelproduct__integration_category__category__icontains=category) # Filtra ProductModel con las condiciones OR products = ProductModel.objects.filter( q_objects).distinct().values_list('name', flat=True) if products: queryset.append({ 'category': category, 'products': list(products) }) return queryset @swagger_auto_schema(tags=['Product']) def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) I expected this view to be placed in the Products tag but it sent me a warning. enter image description here -
Select non-image file in Django ckeditor browser
I previously uploaded a zip file from django_ckeditor, and I want to create a link to that file. So I clicked the "link" button (or Ctrl-K), and then selected the "browse server" button to select my file. However, when I select the file, I see no button to select the file, and the preview pane kept spinning: But when an image is selected, I'm able to select the "Embed image" button: Relative Django setting: CKEDITOR_UPLOAD_PATH = "public/" CKEDITOR_UPLOAD_SLUGIFY_FILENAME = False CKEDITOR_RESTRICT_BY_USER = False CKEDITOR_RESTRICT_BY_DATE = False CKEDITOR_FILENAME_GENERATOR = 'util.func.ckupload_name' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', } } def ckupload_name(fname, request): return f'{uuid.uuid4()}/{fname}' It looks the image functionality, but I'm sure I'm opening this box using the "link" button. Because the files are uploaded to a random folder, I cannot manually enter the link easily. (I verified that if I found the UUID part, I can download the file from web) So the question is: How can I get the link toward the zip file from ckeditor? -
Django: request from RequestFactory on Windows does not include session attribute
My drone pipeline suddenly started failing on Windows only (the Linux pipeline, executing the same tests, works fine). error: assert hasattr(request, 'session'), "The session-based temporary "\ AssertionError: The session-based temporary message storage requires session middleware to be installed, and come before the message middleware in the MIDDLEWARE list Looking at RequestFactory, this does indeed not give a session, but somehow it works on Linux and it used to work on Windows too. What has changed, why? And how should I add a dummy session to the request? test.py class TestDynamicAlertSubscriptionAdminModule(TestCase): def setUp(self): request = RequestFactory().post(path="dummy") request.user = self.user request._messages = messages.storage.default_storage(request) settings.py MIDDLEWARE = [ "django.contrib.sessions.middleware.SessionMiddleware", "django.contrib.messages.middleware.MessageMiddleware", ] INSTALLED_APPS = [ "django.contrib.sessions", "django.contrib.messages", ] -
Django sends post request when I refresh page
In my model I have a class called "Class". Each student in my online school can enroll in a class, so I have a "Enrollment" model: class Enrollment(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) class_name = models.ForeignKey(Class, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, blank=True) active = models.BooleanField(default=True) accepted = models.BooleanField(default=False) and I have a class-detail view which student can enroll in classes using that: def class_detail(request, pk, slug): class_name = get_object_or_404(Class, pk=pk, slug=slug) try: student = Student.objects.get(student_id=request.user.id) except Student.DoesNotExist: student = Student.objects.create(student=request.user) enrolled = None accepted = None try: if Enrollment.objects.get(class_name=class_name, student=student, active=True): enrolled = True except Enrollment.DoesNotExist: enrolled = None try: if Enrollment.objects.get(class_name=class_name, student=student, active=True, accepted=True): accepted = True except Enrollment.DoesNotExist: accepted = None if request.method == 'POST': if not enrolled: form = EnrollmentForm(request.POST) if form.is_valid(): enrollment = form.save(commit=False) enrollment.student = student enrollment.class_name = class_name enrollment.save() else: form = EnrollmentForm() else: form = EnrollmentForm() context = {'class': class_name, 'enrolled': enrolled, 'accepted': accepted, 'form': form, 'student': student} # context = {'class': class_name, 'student': student} return render(request, 'school/class-detail.html', context) and this is my template: {{ class.title}} {% if accepted %} <p><a href="{{ class.class_link }}">Enter</a></p> {% elif enrolled %} <p>You have successfully enrolled.</p> {% else %} <form class="" action="" method="post"> {% csrf_token %} {{ form }} … -
The button doesn't work according to the action
By pressing this button, the seller must close the sell and no one else can bid. This button should be visible only to the seller. However, it is visible to everyone and does nothing. The form is related to the creation of the product page and has a field with the user's name. Thank you in advance for your ideas:) views.py: def close_bid(request, product_id): product = get_object_or_404(Product, id=product_id) bid_info = get_object_or_404(Bid_info, pk=product_id) if request.method == 'POST': user = request.user if user.is_authenticated: if user.id == ProductForm.user.id: bid_info.checkclose = True product.active_bool = True product.save() return redirect('page_product', product_id=product.id) page_product.html: {% if product.active_bool and Bid_info.checkclose %} <p>This is close!</p> {% else %} <form method="post" action="{% url "close_bid" product.id %}"> {% csrf_token %} <button type="button" class="btn btn-danger">Close</button> </form> {% endif %} models.py: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=20) seller_price = models.DecimalField(max_digits=10, decimal_places=2) active_bool = models.BooleanField(default=False) class Bid_info(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name="seller") bid_price = models.DecimalField(max_digits=10, decimal_places=2) checkclose = models.BooleanField(default=False) winner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) -
List of string with Django and Django restAPI
I have setup my Django and Django restAPI and I'm trying to setup my model to have a list of strings. Here's my code model.py import uuid from django.db import models class TagModel(models.Model): name = models.CharField(max_length=100) class EventModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255) tags = models.ManyToManyField(TagModel) class Meta: db_table = "events" ordering = ['-createdAt'] def __str__(self) -> str: return self.title serializers.py from rest_framework import serializers from .models import EventModel, TagModel class TagSerializer(serializers.ModelSerializer): class Meta: model = TagModel fields = '__all__' class EventSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True) class Meta: model = EventModel fields = '__all__' My code works but not what I expected. I tried on postman to do a GET and POST request. The GET response seems to work well, but the POST request works but only with a dictionnary like the following { "title": "My example title", "tags": [{"name":"string"}, {"name":"pokemon"}] } but I wanna send something simpler like this { "title": "My example title", "tags": ["string", "pokemon"] } how to make this happen? Note: I don't use POSTGRESQL -
How do I unit test writing to a CSV file?
I am currently writing a test for a django script that writes some audit log entries to a CSV file. The system takes one CSV file, parses its contents, then adds entries based on the selections within, and saves it again once its all done. The outline of the test is as follows: class ProjectAuditReportExporterTestCase(TransactionTestCase): (...) def test_csv_generation(self): (...) mock_csv_writer = MagicMock() mock_csv_writer.writerow = MagicMock() with patch("external.exporters.csv_overwrite", return_value=mock_csv_writer) as mock_csv_overwrite: it = ImportTask.objects.create( organization=self.organization, user=self.user, data="force_delete", file=ContentFile(csv_buffer.getvalue(), "test_audit_report_exporter.csv"), importer="TasksAuditReportExporter", ) mock_csv_overwrite.assert_called_once_with(it.file, "Task Audit Report") mock_csv_writer.writerow.assert_called() The applicable bits of code for the export process are as follows: @contextmanager def csv_overwrite(file, filename_prefix) -> csv.writer: with tempfile.NamedTemporaryFile() as temp_file, io.TextIOWrapper( temp_file, encoding="utf-8-sig", write_through=True ) as text_file: yield csv.writer(text_file) temp_file.flush() temp_file.seek(0) file.save(f"{filename_prefix}_{now().strftime('%Y-%m-%d')}.csv", temp_file) (...) class EventsAuditReportExporter(BaseCSVImporter): def _handle_row(self, row): log_entries = self._logs_filter(LogEntry.objects.get_for_model(Event), start_date, end_date) with csv_overwrite(self.task.file, "Event Audit Report") as csv_writer: csv_writer.writerow( ( "Event ID", "Action date", "Action actor", "Action", "Event name", "Event date", ) ) for log_entry in log_entries.prefetch_related("actor", "version"): field_dict = log_entry.version.field_dict if field_dict: csv_writer.writerow( ( log_entry.object_id, log_entry.created.isoformat(), log_entry.actor, log_entry.action, field_dict.get("title"), field_dict.get("date"), ) ) I know there are appropriate log entries available, my debugger will always get into the csv_writer.writerow line with out issue. The issue that I have is that … -
Django: Extended User Model not saving changes to database
I have the following extended user class in models.py: Pro_User(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) access = models.BooleanField def access_update(self, Activated:bool): self.access = Activated self.save() However when I call access_update(True) in the shell it does not store the changes permanently, in the next shell session it is just BooleanField again. Any tips are appreciated :) I tried a lot of different things I found on StackOverflow already -
Elasticsearch, Searching by extra field in logging
I'm using Elasticsearch with elastic-apm==6.19.0 configured for Django. After logging an error message like logger.exception( custom_logging_message, exc_info=True, extra={ 'status_code': status_code }, ) I can indeed observe the error containing custom_logging_message in Kibana. In Elasticsearch, I can even use Query DSL to view the document which was created by the above logging event. It also holds the data which was passed to the logger using the extra keyword, as follows: "error": { ..., "custom": { ..., "status_code": 500, } } So far so great, but I want to write a query which is based on one of the extra fields. Like: GET _search { "query": { "range": { "error.custom.status_code": { "gte": 500 } } } } But the result is empty. I tried to figure out whether the respective field is indexed, using the following query: GET _my_error_index/_mapping?pretty. The result did indeed not hold the respective field under "mappings". Is this the reason why I could not use it in the search query? And if so, how to I get it indexed? Is it a setting in the elastic-apm package? I am very new to this topic and appreciate any help. Thank you. -
received channel layer as None in django
I am using channels into python and django project. the project is in docker image and the containers are redis, celery, postgres etc. and the work is to connect to the server and receive messages from the server using the redis for that. But the problem i am facing is i can't connect to the server and receiving the value of channel_layer as none let me provide you the code so that finding issue will be clean and clear so the code i updated in my settings.py file is settings.py `ASGI_APPLICATION = "ucm.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis", 6379)], }, }, }` asgi.py ` import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application from hook.routing import websocket_urlpatterns import hook.routing django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) **hook\\routing.py**`from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import re_path from .ChatConsumer import ChatConsumer websocket_urlpatterns = [ re_path(r'ws/chat/(?P<name>[^/]+)--(?P<wa_number>\d+)++(?P<mobile>\d+)/$', ChatConsumer.as_asgi()), ] application = ProtocolTypeRouter({ 'websocket': URLRouter(websocket_urlpatterns), })`` chatconsumers.py ` import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): #Extract data from payload _payload = await self.receive_json() room_data = f"{_payload['name']}--{_payload['wa_number']}--{_payload['mobile']}" # … -
How to get hierarchal results from models
I have hierarchal django model and it looks like this class Organizator(Model): is_active = models.BooleanField() user = models.IntegerField() clas Task(Model): content = models.CharField() task_id = models.IntegerField() parent = models.ForeignKey('self') organizator = models.ForeignKey(Organizator, related_name='control_taks') class Performer(Model): user = models.IntegerField() task = models.ForeignKey(Task, related_name='tasks') from this given model I am going to get following result like this { "user": 1, "is_active": true, "control_taks": [ { "task_id": 2, "content": "test", "performers": [ { "user": 1, "tasks": [ { "task_id": 3, "performers": [ { "user": 3, "tasks": [] } ] } ] } ] } ] } how can I do this? My code does not return expected result so I did not show here. Any help would be appreciated! -
What does the carat (^) operator do on Django Q objects?
The Django Query documentation mentions three operators which can be used to combine Q objects: Q objects can be combined using the &, |, and ^ operators. But the examples in the docs all focus on | (which is maybe understandable). The & and | operators are (to me at least) fairly obviously analogous to AND and OR. But what does ^ translate to in SQL?