Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF - detail not found if annotate a field from a non-existing-relation
I have a model with a nullable relation. class Relation(models.Model): name = CharField(max_length=255) class MyModel(models.Model): name = CharField(max_length=255) relation = ForeignKey(Relation, null=True, on_delete=models.SET_NULL) I pass the name of the relation into my Serializer. class MyModelSerializer(serializers.ModelSerializer): relation_name = serializers.CharField(read_only=true) class Meta: model = MyModel fields = '__all__' I annotate the relation name in the queryset of my viewset. class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all().annotate(relation_name=F('relation__name') serializer_class = MyModelSerializer Now when I try retrieve an instance of MyModel, which has not a relation to Relation, I got the response: { "detail": "Not found." } Otherwise, if the instance has a relation, the response looks like: { "id": 1, "name": "Test MyModel", "relation": 1, "relation_name": "Test Relation" } I've expected, that the response without a relation would look like: { "id": 1, "name": "Test MyModel", "relation": null, "relation_name": null } Does anyone have in the past a problem with annotation of non existing relation and has an idea how to deal with that? Best regards -
ContentNotRenderedError / image field in serializer (DRF)
I have a model for random Products which has an image field and a default image. I want to make it such that the client doesn't have to send an image when creating a new product through the API (using DRF). Below are the model, serializer and view # Model ... total_stock = models.PositiveIntegerField(default=0) product_image = models.ImageField(upload_to='images', blank=True, default='/static/images/default_product.png') # Serializer class ProductSerializer(serializers.ModelSerializer): product_image = serializers.ImageField(max_length=None, allow_empty_file=False) class Meta: model = Product fields = [ 'total_stock', 'product_image'... ] # View class ProductCreate(generics.CreateAPIView): permission_classes = [IsAuthenticated] queryset = Product.objects.all() serializer = ProductSerializer() In order for the view to accept a payload without an image, I have to modify the serializer like this: class ProductSerializer(serializers.ModelSerializer): product_image = serializers.ImageField(max_length=None, allow_empty_file=False, required=False) # added "required=False" But when I do that, I get the error: The response content must be rendered before it can be iterated over. Request Method: GET Request URL: http://127.0.0.1:8000/product/create/ Django Version: 4.0.5 Exception Type: ContentNotRenderedError Exception Value: The response content must be rendered before it can be iterated over. Exception Location: .../lib/python3.10/site-packages/django/template/response.py, line 127, in __iter__ Python Executable: /.../bin/python Python Version: 3.10.4 ... All the other questions I have investigated are with respect to queries but I'm not making a query … -
Nuxt2-Keycloak-Django Rest Framework Authentication
I've integrated keycloak authentication in my nuxt2 application using nuxt-auth, here my auth configration in nuxt.config.js auth: { strategies: { oidc: { scheme: "openIDConnect", clientId: process.env.KEYCLOAK_CLIENT_ID, endpoints: { configuration: `/keycloak/`, }, responseType: "code", grantType: "authorization_code", scope: ["openid", "profile", "email"], codeChallengeMethod: "S256", token: { property: "access_token", type: "Bearer", name: "Authorization", maxAge: 300, }, refreshToken: { property: "refresh_token", maxAge: 60 * 60 * 24 * 30, }, // acrValues: "1", }, }, redirect: { login: "/", logout: "/", home: `/user`, }, }, Now I want to authenticate my django rest framework API with this client keycloak accesstoken I tried django-oauth-toolkit package for keycloak authentication. and configration INSTALLED_APPS = [ ... "oauth2_provider", "rest_framework", ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", ), "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), } OAUTH2_PROVIDER = { "SCOPES": { "openid": "OpenID Connect", "profile": "User profile information", "email": "User email address", } } while I tried to call my api with the nuxt keycloak access token it returns me 401-Authentication credentials were not provided. Please help me with this scenario or tell me if it possible to authenticate django APIs with nuxt keycloak accesstoken NB: Client used in nuxt and django are different. -
how to customize nested fields serializer through another serializer in drf
File class and Animation are related together And I want to somehow implement the following code serial = AnimationSerializer(instance=Animation.objects.get(id=animationn_id), fields=["duration", "age_rating", {"file": ["name", "description"]}]) or serial = FileSerializer(instance=File.objects.get(id=file_id), fields=["name", "description", {"animations": {"fields": ["duration", "made_by"], "many": True, "read_only": False}}]) actually i don't want write several serializer class. I want to write as little code as possible to achieve this goal. I want to implement the methods of creation and retrieval and update for two models using 2 serializers so that I can use one of the two serializers to create, retrieve, and update instances of that one model. i have two simple model : class File(models.Model): video = 1 PDF = 2 word = 3 all_types = ( (video, "video"), (PDF, "PDF"), (word, "word"), ) type = models.PositiveSmallIntegerField(choices=all_types) name = models.CharField(max_length=30) description = models.CharField(max_length=50) class Animation(models.Model): file = models.ForeignKey("File", on_delete=models.CASCADE, related_name="animations") duration = models made_by = models..CharField(max_length=30) age_rating = models.PositiveSmallIntegerField(validators=[validators.MaxValueValidator(24)]) and i have these serializer class: class DynamicFieldsCategorySerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super().__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed … -
Unknown output_field type in Subquery in Django
I have the following models: class Parent1(models.Model): name = models.CharField(max_length=255) class Parent2(models.Model): parent1 = models.ForeignKey(Parent1) label = models.CharField(max_length=255) class Child(models.Model): parent1 = models.ForeignKey(Parent1) parent2_label = models.CharField(max_length=255) # other fields I am trying to execute the below queries: parent1 = Parent1.objects.first() sq = Child.objects.filter(parent1=OuterRef("parent1"), parent2_label=OuterRef("label")) parents_2 = Parent2.objects.filter(parent1=parent1).annotate(children=Subquery(sq)) So basically what I am trying to execute is if Child model had a fk to Parent2 then I would have prefetched the related child instances of the Parent2 instances. Now at present there is no fk relation between Child and Parent2. The relation is based on the label field between those two. fk will be added later but before that for backwards compatibility I have to execute this query. Now when I try to execute this query then I am getting the following error: FieldError: Cannot resolve expression type, unknown output_field I am using Postgresql db. Now what will be the output_field for the above query that I have to pass? -
save() causing the creation of a new record when trying to update an existing record
So I have the following model: class Session(models.Model): sessionid = models.CharField(max_length=10, primary_key=True) forgepass = models.ForeignKey(ForgeProfile, on_delete=models.CASCADE) programid = models.ForeignKey(TrainingProgram, on_delete=models.PROTECT) program_day = models.IntegerField() hours = models.IntegerField() session_date = models.DateField(default=timezone.now()) verified = models.BooleanField(default=False) def save(self, *args, **kwargs): session_count = Session.objects.all().count() self.sessionid = 'S' + self.forgepass.forgepass + id_gen(session_count) super().save(*args, **kwargs) def __str__(self): return '{} - {}'.format(self.sessionid, self.session_date) When updating an existing record on the backend, a new record will be created with a new sessionid and the updated values instead, while keeping the old record. What exactly am I missing here? -
Django: Streams from cameras stop if there are two of them on a page
I made an application that shows the image from the camera after detection and calculation in real time. I show the video on the site. If I show a stream from one camera <img src="{% url 'video_feed' %}" alt="Video Feed 1" width="800" height="600"> it works perfectly. If there are two streams, but from the same camera - ideal. <img src="{% url 'video_feed' %}" alt="Video Feed 1" width="800" height="600"> <img src="{% url 'video_feed' %}" alt="Video Feed 1" width="800" height="600"> If two streams are from different cameras, it freezes almost completely. I open each stream separately - perfect. http://127.0.0.1:8000/video_feed/ http://127.0.0.1:8000/second_video_feed/ What could be the reason? Even tried threading, but to no avail. The final version of views.py I enclose from django.views.decorators import gzip from .object_counter import CountObject_Camera1, VideoCapture_Camera1, CountObject_Camera2, VideoCapture_Camera2 from django.shortcuts import render import cv2 import threading rtsp_url1 = "rtsp:///cam/realmonitor?channel=1&subtype=00&authbasic=[AUTH]" rtsp_url2 = "rtsp:///cam/realmonitor?channel=1&subtype=00&authbasic=[AUTH]" count_object_instance1 = CountObject_Camera1(rtsp_url1) count_object_instance2 = CountObject_Camera2(rtsp_url2) video_capture1 = VideoCapture_Camera1(rtsp_url1) video_capture2 = VideoCapture_Camera1(rtsp_url2) lock1 = threading.Lock() lock2 = threading.Lock() @gzip.gzip_page def video_feed(request): def generate(camera_instance, count_object_instance, lock): while True: with lock: frame = camera_instance.read() annotated_frame = count_object_instance.process_frame(frame) _, buffer = cv2.imencode('.jpg', annotated_frame) frame_bytes = buffer.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n') return StreamingHttpResponse(generate(video_capture1, count_object_instance1, lock1), content_type='multipart/x-mixed-replace; boundary=frame') def … -
Drawing price history chart in Django
i am trying to draw a chart with django, the django view will fake some data(price and timestamp) html will draw line chart using chartjs. The console display chart.js:19 Uncaught Error: This method is not implemented: Check that a complete date adapter is provided. even though i follow this chartjs getting start and include <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> i also run npm install moment chartjs-adapter-moment --save-dev and npm install chart.js My views: def price_history(request, product_id): form = ProductNameForm() product = Product.objects.get(pk=product_id) # Create some dummy price history data for testing price_history_data = [] today = datetime.now() for i in range(1, 11): # Generate data for the last 10 days date = today - timedelta(days=i) price = float(product.current_price - (randint(1, 10) * 10)) # Example: Randomly decrease price price_history_data.append({ 'timestamp': date.strftime('%Y-%m-%d'), 'price': price, }) return render(request, 'price_history.html', {'product': product, 'price_history_data': price_history_data, 'form':form}) My template: {% block content %} <div class="container"> <h1>Price History</h1> <!-- Price history chart container --> <!-- Price history chart container --> <canvas id="priceChart" width="400" height="200"></canvas> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script> <script> // Extract timestamps and prices let timestamps = {{ price_history_data | safe }}; let prices = timestamps.map(entry => entry.price); timestamps = timestamps.map(entry => entry.timestamp); // Get the canvas element … -
I can't log in with a registered user
I can register my users, but I can't log in with these users. After registering the users, they are automatically logged in, so this is the only moment I can access the Profile area. After logging out, I can't log in any user except my superuser. I have try several ways and can't seem to figure it out. here are my files: #models.py from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError("O endereço de email é obrigatório") user = self.model( username=username, email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password): user = self.create_user( username=username, email=email, password=password, ) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Cadastro(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=75, unique=True) data = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = "username" EMAIL_FIELD = "email" REQUIRED_FIELDS = ["email"] def __str__(self): return self.username #forms.py from django import forms from base.models import Cadastro from django.contrib.auth.forms import AuthenticationForm class CadastroForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = Cadastro fields = ("username", "email", "password") class LoginForm(AuthenticationForm): username = forms.CharField( widget=forms.TextInput(attrs={"class": "form-control"}), required=True ) password = forms.CharField( widget=forms.PasswordInput(attrs={"class": … -
How to set refresh token expire of drf social oauth2?
How can we set refresh token expire of drf social oauth2. I try to use this but not work(Work only access token). OAUTH2_PROVIDER = { 'REFRESH_TOKEN_EXPIRE_SECONDS': 1, #set to 1 second for test 'ROTATE_REFRESH_TOKEN': false, } Anyone can help? -
webRTC audio - Don't know how to resume streaming after closing/stoping it
I was trying webRTC for a chatbot with voice prompts. I was successful on incorporating the voice prompts to the chat, but i have a problem. I noticed the mediaRecorder.stop doesn't stop the streaming, so the red circle in the window will not dissapear. I want it to only be streaming when the user is recording the message. What i tried: I searched other solutions and found that this line will successfully end the streaming: stream.getTracks().forEach( track => track.stop() ); The problem is, I don't know how to resume the streaming after that, the record button turns unresponsive. This is my entire code, sorry for not providing a more compact one, i'm not too keen with javascript to leave things behind: let mediaRecorder; let recordedChunks = []; let isRecording = false; // Track the recording state // Function to start recording function startRecording() { if (mediaRecorder && mediaRecorder.state === 'inactive') { mediaRecorder.start(); isRecording = true; } } // Function to stop recording function stopRecording() { if (mediaRecorder && mediaRecorder.state === 'recording') { mediaRecorder.stop(); isRecording = false; } } // Function to initialize the MediaRecorder function initializeMediaRecorder() { if (!mediaRecorder) { // Initialize the MediaRecorder with audio constraints navigator.mediaDevices .getUserMedia({ audio: … -
Getting this error while using Django Tenant with DRF Exception: Can't create tenant outside the public schema. Current schema is ... while using DRF
So I am using django tenant with django rest framework. I have two created apps users and students. For users I was able to setup the model, serializer and viewset and create users using the viewset with no issues. Mirrored most of the logic for creating users in students but been having issues creating a student using the API. Keep getting the error Exception: Can't create tenant outside the public schema. Current schema is concord. I have tried finding a similar issue on stack overflow but not seen anything similar. Would appreciate any help. Find relevant snippets below # MIDDLEWARE # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#middleware MIDDLEWARE = [ "django_tenants.middleware.main.TenantMainMiddleware", "django.middleware.security.SecurityMiddleware", "corsheaders.middleware.CorsMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.common.BrokenLinkEmailsMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] # ------------------------------------------------------------------------------ SHARED_APPS = ( "django_tenants", # mandatory "dew_school_management_system.school", "django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sessions", "django.contrib.sites", "django.contrib.messages", "django.contrib.staticfiles", # "django.contrib.humanize", # Handy template tags "django.contrib.admin", "django.forms", "django_filters", "dew_school_management_system.users", "crispy_forms", "crispy_bootstrap5", "allauth", "allauth.account", "allauth.socialaccount", "django_celery_beat", "rest_framework", "rest_framework.authtoken", "dj_rest_auth", "corsheaders", "drf_spectacular", ) TENANT_APPS = ( "django.contrib.auth", "django.contrib.sessions", "dew_school_management_system.users", "dew_school_management_system.students", # Your stuff: custom apps go here ) # https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps INSTALLED_APPS = list(SHARED_APPS) + [ app for app in TENANT_APPS if app not in SHARED_APPS ] # TENANT CONFIGURATION TENANT_MODEL = "school.School" TENANT_DOMAIN_MODEL = "school.SchoolDomain" I … -
AttributeError: 'Response' object has no attribute 'streaming' in packages\django\middleware\common.py
Using requests we are unable to get a 200 success code due to either a bug in the common file or a wrong way of sending the request or receiving the response. Here are the technical details: Calling script import requests try: post_data = {'langs': langs, 'langs_json': []} # filling post_data.. response = requests.post(api_call_url, json=post_data, verify=False) return response except Exception as e: return JsonResponse({}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) Serving script @csrf_exempt def api_end_point(request): try: data = json.loads(request.body.decode('utf-8-sig')) with open(os.path.join(r'assets\i18n', f'fr.json'), 'w', encoding='utf-8-sig') as f: json.dump(data['langs_json'][0], f) with open(os.path.join(r'assets\i18n', f'en.json'), 'w', encoding='utf-8-sig') as f: json.dump(data['langs_json'][1], f) # All works above.. the issue has something to do with the response itself.. response = JsonResponse(dict(status=True), safe=False, status=status.HTTP_200_OK) response.status_code = 200 # trying to solve.. return response except Exception as e: response = JsonResponse(dict(status=False), safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) response.status_code = 500 # trying to solve.. return response Error msg File "C:\Users\***\Desktop\****\*****\*****\venv\lib\site-packages\django\middleware\common.py", line 112, in process_response if not response.streaming and not response.has_header('Content-Length'): AttributeError: 'Response' object has no attribute 'streaming' common.py snippet def process_response(self, request, response): """ When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True. """ # If the given URL is "Not Found", then … -
Byte range requests in Django REST + nginx (dokku)
In my Django application, I have a Video model with a file FileField that represents a user-uploaded video. I serve these files via a Django REST API view that looks like this: class VideoViewSet(viewsets.ModelViewSet): queryset = Video.objects.all() serializer_class = VideoSerializer def retrieve(self, request, *args, **kwargs): instance = self.get_object() file = instance.file response = FileResponse( file, as_attachment=True, ) response["Content-Disposition"] = 'attachment; filename="video.mp4"' response["Accept-Ranges"] = "bytes" return response the frontend accesses the video like this: <video playsinline controls> <source type="video/webm" :src="videoUrl"/> <p> Videos are unsupported in your browser </p> </video> The application is deployed using dokku, which has gunicorn and nginx sit in front of Django. The problem is: in production, when the video player is opened, I am unable to seek. The video just proceeds from timestamp 00:00 all the way to the end, even if I drag the video timeline thumb to other positions. I learned that has to do with byte range requests, and not supporting them is the cause of not being able to seek while the video is playing. Adding response["Accept-Ranges"] = "bytes" in my viewset makes it work locally, but when I push to production the problem is still there. What can I do to solve … -
'TranslateCategory' object is not iterable in DRF
I use Django Rest Framework and run my code with gunicorn. And i got this error 'TranslateCategory' object is not iterable. Traceback: Request Method: GET Request URL: http://oralbekov.dias19.fvds.ru/api/translate/categories/1/ Django Version: 3.2.16 Python Version: 3.8.10 Installed Applications: ['jazzmin', 'modeltranslation', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', 'questions.apps.QuestionsConfig', 'calendartodo.apps.CalendartodoConfig', 'rites.apps.RitesConfig', 'map.apps.MapConfig', 'news.apps.NewsConfig', 'translate.apps.TranslateConfig', 'info.apps.InfoConfig', 'reportederrors.apps.ReportederrorsConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/var/www/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/var/www/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/var/www/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/var/www/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler return func(*args, **kwargs) File "/var/www/hajjum/translate/views.py", line 30, in categories_id return Response(serializer.data ,status=status.HTTP_200_OK) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 768, in data ret = super().data File "/var/www/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 253, in data self._data = self.to_representation(self.instance) File "/var/www/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 686, in to_representation return [ Exception Type: TypeError at /api/translate/categories/1/ Exception Value: 'TranslateCategory' object is not iterable Here … -
How to make dynamic menu & navbar from database in Django
I am developing a digital marketing agency website and there are services that this agency provides. There are 4 categories and each category has its own services. In the navbar there is a dropdown menu, when you hover "Our Services" there is a list of categories and services that below the categories. So I want to make this dynamic. The categories and the services that below the categories should come from database. But with my codes and tries; dropdown menu shows nothing. Here is my codes: Models.py from django.db import models from ckeditor.fields import RichTextField from django_resized import ResizedImageField class Category(models.Model): name = models.CharField(max_length=100, blank=True) slug = models.SlugField(max_length=100, unique=True, null=True) def __str__(self): return self.name class Service(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True,) available = models.BooleanField(default=True) slug = models.SlugField(max_length=100, unique=True, null=True) def __str__(self): return self.name views.py def navbar_services(request): categories = Category.objects.all() services = Service.objects.filter(category=categories) context = { 'categories': categories, 'services': services } return render(request, 'partials/_navbar.html', context) partials/_navbar.html <li class="menu-item main-nav-on menu-item-has-children"> <a href="#"><span class="rolling-text">Our Services</span></a> <ul class="mega-menu-01 sub-menu elements" style="display: block;"> {% for cat in categories %} <li class="single-mega"> <a class="tag" href="#">{{cat.name}}</a> <ul class="main-wrapper" style="display: block;"> {% for item in cat.service_set.all %} <li class="menu-item"><a class="menu-link" href="banner.html">{{ item.name }}</a></li> {% … -
How to properly select tags in jqXHR returned by jQuery $.post
I am building a barebones webapp in django with jQuery. I am running into an issue properly getting at HTML elements that are returned in jqXHR from a $.post call. $.post is called from a js function that bundles up some timestamp data and hits a django endpoint, which in return serves an HTML file that contains a couple <tbody> tags and a <div>, which are inserted into the main page by jQuery .replaceWith calls. The tangle I'm running into is that jQuery is able to access and handle the <tbody> elements just fine, but cannot locate the <div>. Code below has been synopsized a bit to save space. js function that generates the post call and handles insertion to main page funciton getDbUpdate(){ let _WaitTimes = JSON.stringify(compileWaitTimes()); $.post("{% url 'checkForDbUpdate' %}", {_WaitTimes, csrfmiddlewaretoken: '{{ csrf_token }}'}, function(data, status){ if (status!='nocontent'){ const queueTableHTML = $(data).filter("#queueTableBody").html(); //works const archiveTableHTML = $(data).filter("#archiveTableBody").html(); //works const targetDivElet = $(data).filter("#targetDivElet").html(); //returns nothing $('#queueTable > tbody').replaceWith(queueTableHTML); $('#archiveTable > tbody').replaceWith(archiveTableHTML); $('#targetDivElet').replaceWith(targetDivElet) }; ); }; django endpoint from views.py def checkForDbUpdate(request): if request.method == "POST": # --> do some database operations # return http 204 if nothing has changed between polls if ids_from_request==ids_from_model: response = HttpResponse() response.status_code=204 return … -
How do I set up a Django user for use in a Selenium test case with the setUp method?
I am working to create Selenium unit tests for my code. I have a simple login form: <form method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="f00b4r"> <div id="div_id_username" class="form-group"> <label for="id_username" class="requiredField">Callsign <spanclass="asteriskField">*</span> </label> <div> <input type="text" name="username" autofocus="" maxlength="150" class="textinput textInput form-control" required="" id="id_username"> </div> </div> <div id="div_id_password" class="form-group"> <label for="id_password" class="requiredField">Password <span class="asteriskField">*</span> </label> <div> <input type="password" name="password" autocomplete="current-password" class="textinput textInput form-control" required="" id="id_password"> </div> </div> <button class="btn btn-primary" type="submit">Login</button> </form> And this is the test case: class TestLoginFormFirefox(LiveServerTestCase): def setUp(self): self.driver = webdriver.Firefox() self.good_user = User.objects.create_user(username="unittest", password="this_is_unit") def tearDown(self): self.driver.close() def test_index_login_success(self): """ When a user successfully logs in, a link to their profile should appear in the navbar """ self.driver.get('http://127.0.0.1:8000/login') username_field = self.driver.find_element(by=By.ID, value='id_username') password_field = self.driver.find_element(by=By.ID, value='id_password') username_field.send_keys('unittest') password_field.send_keys("this_is_unit") login_button = self.driver.find_element(by=By.CLASS_NAME, value="btn-primary") login_button.send_keys(Keys.RETURN) # needs time to render sleep(3) id_profile_link = self.driver.find_element(by=By.ID, value='id_profile_link').text assert id_profile_link == 'unittest' The test is simple: if the user specified in the unittest setUp method is able to successfully log in, assert that the user's username is a part of a link in the next page. The rub here is that the setUp method creates the user object, but the login fails. This persisted until I made a user in the project's … -
How to update Docker interpreter when requirements.txt is updated
i add some library to requirement.txt but Docker interpreter in pycharm do not update and when i install some library in dockr container i get this error some error and warning. this is warning = WARNING: The directory '/home/shop/.cache/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you should use sudo's -H flag. and this is error = ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: '/py/lib/python3.11/site-packages/urllib3' Check the permissions. you can see my docker file. FROM hemanhp/djbase:4.2.4 COPY ./requirements /requirements COPY ./scripts /scripts COPY ./src /src WORKDIR src EXPOSE 8000 RUN /py/bin/pip install -r /requirements/development.txt RUN chmod -R +x /scripts && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ adduser --disabled-password --no-create-home shop && \ chown -R shop:shop /vol && \ chmod -R 755 /vol ENV PATH="/scripts:/py/bin:$PATH" USER shop CMD ["run.sh"] -
Using Fetch in REACT for PUT/PATCH doesn't work for me
Hello in my React App I use this specific comportement to handle modification (status change actived/deactived) const handleActifEspece = (index, statutActif) => { let especeAActiver = especes.find(espece => espece.id === index) especeAActiver.actif = statutActif console.log(JSON.stringify(especeAActiver)) fetch(`http://localhost:8000/api/especes/${index}`, { method: 'PUT', headers: { 'Content-type': 'application/json; charset=UTF-8',}, body: JSON.stringify(especeAActiver) }) .then(response => response.json()) .then(data => { snackBar.openSnackbar("Espèce modifiée !") setSnackMode('success'); setEspeces([...especes, data]) }) .catch(error => { console.error("Erreur pendant l'activation de l'espèce", error); snackBar.openSnackbar("Espèce non modifiée !") setSnackMode('error'); }) }; When I click on button in log I've got specific data : The JSON Stringigy of ma var is : {"id":40,"nom":"Test 6","gaf":false,"actif":true,"instance":{"id":1}} I've got ERROR 500 I use the DjangoRestFramework to handle API When I copy past the dat the url and got to PUT here is the error in Swagger : { "instance": [ "Incorrect type. Expected pk value, received dict." ] } It's working well for POST (add) and DELETE but for PUT or PATCH it doesn't :( Please help ;) -
Why did my API get duplicated in swagger?
I created a couple of new APIs to request and calculate scores from a giver user, one is supposed to be a GET (Get Score), and the other one is just a PATCH (Calc Score), for whatever reason the later one got duped into an additional GET that I never made nor did I give it a URL, what did I do wrong? Can I fix it or is it an inherent property of PATCH methods to create an auxiliary GET? As seen here -
How to comunicate database and web app which are in two different serevers?
I have a mysql database and a django web app but they are in two separated servers (two laptops) and o I want to know how can I comunicate them. Does anyone have a manual that i can read or watch? I'm expecting for a manual/guide to lear how to achieve it <- sorry for repated that. -
Grab last url parameter in referer
Is there a way without actually parsing the data wit a custom function to get the last piece of a url in django? so if the url looks like this http://192.168.1.100/test/article/1 And i just want to be able to grab the 1 without actually having query paramaters in the url. -
How to assign user for Celery tasks?
I'm planning a project that will make use of Celery tasks that will perform CRUD operations on my models. In addition, I have Signals in place that will listen for those CRUD operations and I want to specifically log that it was a Celery task (or a Celery task user) performing the operation. So would I accomplish assigning a User to my Celery workers so that whenever they interact with my models I can track that? @receiver(pre_save, sender=Location) def location_pre_save(sender, instance, update_fields=None, **kwargs): try: old_location = Location.objects.get(id=instance.id) # Log Celery user has updated this Location except Location.DoesNotExist: # Log Celery user has created this Location -
Relationship Type Between Comments and an App
I'm new to setting up database schemas and am working a problem where I have multiple models that should contain a comments section. I'm using Django with SQLite for reference. For example there are Projects which are made up of Tasks. Each Project and Task should have a comments section. Projects can contain many Tasks, but one task will only point to one Project. I have one model for Comments that will ever only point to one Project or one Task, but Projects and Tasks will have multiple Comments. I think what I want is a Many to one relationship on the Comments model, but then I would need multiple FK fields depending on where the comment is attached (Project or Task). My full app will have 8-10 locations where we'd want to have comments. Thanks in advance!