Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
the html template fragment is not updated correctly when working with ajax
I have a Django template that displays a hierarchy of workers using the django mttp library. {% extends "base.html" %} {% load static mptt_tags %} {% block content %} <ul class="root" > <button type="button" id="full-button">Click</button> {% recursetree object_list %} <li> {{node.first_name}} {{node.last_name}} {{node.middle_name}} {% if not node.is_leaf_node %} <ul class="children" id="update"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="{% static "scripts/treeOpen.js" %}"></script> {% endblock content %} When the page is first loaded, only the first two levels of the hierarchy are displayed. The task is to implement lazy loading so that the user clicks on the button and only after that all levels are loaded. I am trying to do this using Ajax $(document).ready(function () { $('#full-button').click(function (event) { console.log("work") openFull(); }); function openFull() { $.ajax({ url: '/tree/', method: 'GET', data: { 'full': 1 }, success: function (data) { console.log('success') $('.root').html(data); }, error: function (xhr, textStatus, errorThrown) { console.log('Error ajax request: ' + errorThrown); } }); } }); and in fact, in the console, I have a success suppression database, that is, ajax works correctly, but the code fragment is not updated correctly. I have such a problem as on the screen … -
django: Unsupported lookup for ForeignKey annotated fields
In a django application, I have a Question model with a custom manager: class QuestionManager(models.Manager): def get_queryset(self): return QuestionQS(self.model).get_queryset() class Question(models.Model): objects = QuestionManager() text = models.CharField(max_length=255) label = models.CharField(max_length=40) and a Choice model which has a foreign key to Question: class Choice(models.Model): question = models.ForeignKey(Question, related_name="choices", on_delete=models.PROTECT) text = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) In my Queryset class I have a custom annotation (annotate_flages method to annotate status) that I expect it to be included in every queryset and another custom annotation (extra_annotations method that annotates is_editable) which I want to include manually: class QuestionQS(models.QuerySet): def get_queryset(self): return self.annotate_flags() def annotate_flags(self): qs = self.annotate( status=Case( When(label__icontains="active", then=Value(1)), When(label__icontains="closed", then=Value(0)), default=Value(0), output_field=IntegerField(), ) ) return qs def extra_annotations(self): one_hour_ago = timezone.now() - datetime.timedelta(hours=1) return self.prefetch_related( Prefetch( "choices", queryset=Choice.objects.annotate( is_editable=Case( When( Q(Q(created_at__gt=one_hour_ago) & Q(question__status=1)), then=True, ), default=False, output_field=BooleanField(), ) ), ) ) My problem is that the default annotations (status) are included in the querysets but I do not have access to them from my custom extra_annotations method. When calling the custom method like: questions = Question.objects.get_queryset().extra_annotations() I get unsupported lookup error: Unsupported lookup 'status' for ForeignKey or join on the field not permitted. -
Django queryset filter on a ManyToMany with custom fields
I have the following Django models Block and Condition that are related to eash other through a custom ManyToMany relationship which has customs fields and a custom DB table: from django.db import models class CustomCondition(models.Model): name = models.CharField("custom condition name") class Meta: db_table = "custom_conditions" def __str__(self) -> str: return self.name class BlockCondition(models.Model): block = models.ForeignKey( "Block", related_name="block_condition_as_block", on_delete=models.CASCADE, ) custom_condition = models.ForeignKey( "CustomCondition", related_name="block_condition_as_custom_condition", on_delete=models.CASCADE, ) choice = models.CharField( "choice", choices=[ ("NO_CONDITION", "No condition"), ("ACTIVATED", "Activated"), ("NOT_ACTIVATED", "Not activated"), ], default="NO_CONDITION", ) class Meta: db_table = "block_conditions" def __str__(self) -> str: return self.custom_condition.name class Block(models.Model): name = models.CharField("name", null=False) block_conditions = models.ManyToManyField( CustomCondition, through="BlockCondition", blank=True, default=None, related_name="blocks_as_block_condition", ) class Meta: db_table = "blocks" Now I want to filter blocks for each condition name and where that condition name is activated: for c in CustomCondition.objects.all(): if c.name: filtered_blocks = Block.objects.filter( block_conditions__custom_condition__name=c.name ) filtered_blocks = filtered_blocks.filter( block_conditions__choice__in=["ACTIVATED", "NO_CONDITION"] ) print(filtered_blocks) But I get the following Django error: django.core.exceptions.FieldError: Unsupported lookup 'custom_condition' for ForeignKey or join on the field not permitted. What am I doing wrong here? -
Django Parler Models + Prepopulated Fields issue
I am trying to use django-parler to translate my models. I am using TranslateableModel and TranslatedFields. This is what my class looks like: class Category(TranslatableModel): translations = TranslatedFields( category_name = models.CharField(_('name'), max_length=50, unique=True), description = models.TextField(_('description'), max_length=255, blank=True), ) slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(_('image'), default='default_category_image.jpg', upload_to='category_photos') But I get this error: **django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'categories.admin.CategoryAdmin'>: (admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'category_name', which is not a field of 'categories.Category'.** The error is caused because in my model's admin class slug is a prepopulated field: class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('category_name', )} If I put the slug field within the TranslatedFields I get the errors: <class 'categories.admin.CategoryAdmin'>: (admin.E027) The value of 'prepopulated_fields' refers to 'slug', which is not a field of 'categories.Category'. <class 'categories.admin.CategoryAdmin'>: (admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'category_name', which is not a field of 'categories.Category'. How would I fix this error while still having a slug in my model? -
Access values of manyToMany field before saving
This is my Classroom model: class Classroom(models.Model): name = models.CharField(max_length=120) faculty = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='faculty') students = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='students') def save(self, *args, **kwargs): for faculty in self.faculty.all(): if not faculty.user_type == 'faculty': raise ValidationError('Only users with user type as \'faculty\' can be assigned as faculty to a classroom') for student in self.students.all(): if not student.user_type == 'student': raise ValidationError('Only users with user type as \'student\' can be assigned as students to a classroom') return super(Classroom, self).save(*args, **kwargs) def __str__(self): return self.name The user model has a property called user_type which is either faculty or student. In the Classroom model I want to make sure that only users with user_type as faculty can be selected as faculty and similarly for students. On trying to add data using django admin, I receive the following error: ValueError at /admin/classroom/classroom/add/ "<Classroom: Some Class>" needs to have a value for field "id" before this many-to-many relationship can be used. Not sure how to fix it, kindly guide. Thanks in advance. -
How to implement `others` for a Django Model Choices-CharField?
I have a Django model that has several CharFields. A lot of these represent information of the type Item Type 1 Item Type 2 Others The usual way of defining choices for a CharField is models.CharField( max_length=255, choices=ChoiceList.choices, # Defining Choices ) As you would have guessed, this fails to meet my requirements since I cannot pass it anything(Others) apart from the pre-defined choices. I cannot discard the choices parameter since I need the model to have the choices information for each field. This will be used to fetch all legal options for a particular field. I tried using a custom validator function def validate_choice(value, choices): if value == "Others:": print(value, choices) valid_choices = [choice[0] for choice in choices] if not value.startswith("Others:") and value not in valid_choices: raise ValidationError(f"{value} is not a valid choice") (For simplicity, I defined my logic as Either the value is in the Choice List Or it starts with Others: (To indicate that it is a deliberate Other value) And subsequently, I modified the CharField as follows, to use the new Validator Function models.CharField( max_length=255, choices=IPCSections.choices, validators=[partial(validate_choice, choices=ChoiceList.choices)], ) I then noticed that The Choice validation (By Django) happens before the custom validator is called. Which, … -
Django no reloading
I am working on django project, and I need a page switching without reloading, it should be switched between pages smoothly like react. Can I achieve this? I asked ChatGPT, and tried bunch of examples, but it never helped -
How do I make APIs calls between django and Next.js 13 while being on the server side?
I am making a chat app using nextjs 13 and django as backend. But I'm stuck in authentication and other api calls which requires bearer. If I logged in then how can I save the tokens to the server because sometimes I want to make api calls from sever and may this requires bearer. Also if I'm doing it from client If I logged in from client directly to the api it'll save the cookies but If how do I check before requests that if it's expired or any problems Thanks 😊 I made a wrapper using next-auth and calling login function from signIn of next-auth. This saves session in the server but when it's comes to client I would need bearer from server and I have to use until useSession available. -
Daphne Django deployment error 'Exited with status 1/FAILURE' on linux
I have been struggling with this error for hours, when I try to start my daphne.service, shows up this error after executing the command systemctl status daphne.service. I am folliwing this tutorial: https://github.com/mitchtabian/HOWTO-django-channels-daphne . I am using Gunicorn, Nginx and Redis that are working correctly. Error: × daphne.service - WebSocket Daphne Service Loaded: loaded (/etc/systemd/system/daphne.service; disabled; preset: enabled) Active: failed (Result: exit-code) since Sun 2024-04-21 00:37:25 UTC; 31s ago Duration: 676ms Process: 2998 ExecStart=/home/franreinaudo/venv/bin/python /home/franreinaudo/venv/bin/daphne -b 0.0.0.0 -p 8001 core.asgi:application (code=exited, status=1/F> Main PID: 2998 (code=exited, status=1/FAILURE) CPU: 673ms Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: daphne.service: Scheduled restart job, restart counter is at 5. Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: Stopped daphne.service - WebSocket Daphne Service. Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: daphne.service: Start request repeated too quickly. Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: daphne.service: Failed with result 'exit-code'. Apr 21 00:37:25 test-db.southamerica-west1-a.c.farm-control-test.internal systemd[1]: Failed to start daphne.service - WebSocket Daphne Service. daphne.service [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root WorkingDirectory=/home/franreinaudo/test-db ExecStart=/home/franreinaudo/venv/bin/python /home/franreinaudo/venv/bin/daphne -b 0.0.0.0 -p 8001 core.asgi:application Restart=on-failure [Install] WantedBy=multi-user.target settings.py """ Django settings for core project. Generated by 'django-admin startproject' using Django 5.0.1. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see … -
How do I get django to work with websocket or django channels?
I want to use django holding with django channels I'd like to know how is it possible to do it? Is there a bookstore for that? I want The library or the procedure ? how to install and use django tenant with django channels ? -
Django + React Axios Network Error: Access-Control-Allow-Credentials expected 'true'
I am working on a web app running React on the front end and Django on the back end and am running into a issue when sending api requests to the back end. When attempting a POST or GET request, there occurs a Axios Network Error popping up on the site reading: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/is_authenticated/. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’). Nevertheless, when inspecting the network request in Firefox, the JSON response does contain the correct data and has a 200 OK status. Just a warning appears "Response body is not available to scripts (Reason: CORS Missing Allow Credentials)". My current backend settings using CorsMiddleware are INSTALLED_APPS = [ ... 'app', 'corsheaders', 'rest_framework', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOW_CREDENTIALS: True CSRF_COOKIE_SECURE = False, CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:3000', 'http://127.0.0.1:8000', 'http://localhost:3000', 'http://localhost:8000', ] When sending the request I have the current axios post call. axios.post(`http://localhost:8000/login/`, request, { withCredentials: true }) .then(({ data }) => { if (data.warning) return; localStorage.setItem("currentUser", data.user); }); Is there a setting I am overlooking or specific error in my code? Or are there certain front-end settings on Axios … -
How to log in the celery log, outside celery tasks (inside a django view)?
Suppose an endpoint in a django project def my_view(request, my_id): if is_request_valid(request): logger = logging.getLogger('celery.task') logger.info('Starting a task for a thing with ID %i', my_id) my_cool_task.apply_async() Now, according to the celery docs this may log, since A special logger is available named “celery.task”, you can inherit from this logger to automatically get the task name and unique id as part of the logs. But it works only inside a task. Also, I did play with setting some logging variable inside settings.py, and then reassigning the celery's logging. Did play with the CELERY_WORKER_HIJACK_ROOT_LOGGER, but even when I use the root logger, the logs do not appear in the console. Nor using getLogger("celery") does not help. This seems like a simple thing to do, but I'm struggling all day to do this, please help. -
Why doesn't request.POST show values added using javascript after django form has been rendered
I am trying to update a django form according to user clicks. I allow the user to add more form tags on the DOM by clicking a button, add a value to it and submit when the user is done. I have used modelForm to build the initially part of the form which was rendered in the template. But when the form is submitted it only shows values that are part of the ReportForm class which inherits forms.ModelForm. Here is my report class: class ReportForm(forms.ModelForm): date_resolved = forms.DateField(widget=forms.DateInput(attrs={ 'name': 'date_resolved', 'type': 'date', }), label="Date resolved (ignore if not):") bias_score = forms.IntegerField(widget=forms.NumberInput(attrs={ 'type': 'range', 'width': '100%', 'value':0, 'min': 0, 'max': 10, 'step': 1, 'style': "padding: 0;" }), label="Bias Score (between 0 and 10)") class Meta: model = Reports fields = ['date_resolved', 'tags', 'bias_score'] and this is what the report class looks like class Reports(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) conversation = models.ForeignKey(Conversations, on_delete=models.CASCADE) tags = models.ManyToManyField(Tags, null=True, blank=True) bias_score = IntegerRangeField(min_value=1, max_value=10) resolved = models.BooleanField(default=False) date_resolved = models.DateField(blank=True, null=True) date_added = models.DateField(auto_now_add=True) The javaScript is bit long but here is the most importtant part: function create_tags(){ let label_text_content = null if (IS_PROMPT == true){ IS_PROMPT = false INPUT_COUNTER +=1 label_text_content = 'Prompt:' … -
in Django admin page. How can the entry be changed based on a change in the value of a field?
i use django 5 and i have this code when i choice 'D' the doctor field must active if i change to 'H' the doctor must deactive and hospital become active and so class InputMovment(models.Model): SOURCE_MOVE = { 'D':_('doctor'), 'H':_('hospital'), 'C':_('company'), 'O':_('other'), } source = models.CharField( max_length=1, choices=SOURCE_MOVE, default='D', verbose_name=_("source"), db_index=True) move_number = models.CharField(max_length=20, db_index=True, verbose_name=_('number')) doctor = models.ForeignKey('Doctor', null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('اdoctor')) hospital = models.ForeignKey('Hospital', null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('اhospital')) company = models.ForeignKey('Company', null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('اcompany')) persone = models.CharField(max_length=50, null=True, blank=True, db_index=True, verbose_name=_('other')) description = models.TextField(verbose_name=_('description')) I tried to find a function to change the field, like change_field or something like that but I could not find it Does anyone have any idea for a solution? -
(Django) My function runs twice for no reason
this is my view: def add_to_cart (request, pk): item = models.Product.objects.get(product_id = pk) user = request.user custom_user = models.CustomUser.objects.get(user = user) cart = models.Cart.objects.get(user = custom_user) if cart_products == "": cart.products = f"{str(pk)}={item.product_name}={item.product_price}" else: cart.products += f":{str(pk)}={item.product_name}={item.product_price}" print(cart.products) print(cart) cart.save() return redirect("/") And this is my url: path('products/add-cart/<pk>', views.add_to_cart, name="add_to_cart") Pretty simple. But when I visit 127.0.0.1:8000/products/add-cart/1 url, If it is my first visit for this url (which means if cart_products == "" is True, It works alright and this happens: Then, when I visit url for second time, then this happens: This is very weird because it added 2 more products. The thing is, it adds 1 or 3 sometimes. Absolutely not stabil. This is very weird and my code is very simple. I can not understand it. -
Why does this appear when run my server in django?
Why do I get the following when I run my server in VS code? This is my project file views urls.py in demo urls.py in myapp setting settings The site when I run python manage.py runserver I have tired almost everything from creating a new urls file in myapp, deleting the old one to eating paper. Yes myapp is added in setting. I am running this in VS code. Can someone help figure out the problem? -
Problem with signals logedd_in and logedd_out
signals.py from django.contrib.auth.signals import user_logged_in, user_logged_out from django.dispatch import receiver print("import nice") @receiver(user_logged_in) def login_logged_in(sender, request, user, **kwargs): print("login nice") @receiver(user_logged_out) def login_logged_out(sender, request, user, **kwargs): print("logout nice") "import nice" is shown on the console. "login nice" is not shown on the console. "logout nice" is not shown on the console. apps.py from django.apps import AppConfig class ApplicationConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'application' def ready(self): print("ready nice") import application.signals "ready nice" is shown on the console. init.py default_app_config = 'application.apps.ApplicationConfig' import application.signals What could be happening? pls help me I use debug messages to identify which function is not running correctly -
Django rest session authentification postman
I've customised django auth method: class MyBackend(ModelBackend): def authenticate(self, request, phone=None, otp=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(phone=phone) except UserModel.DoesNotExist: return None else: if user.otp == otp: # user.otp = None # user.save() return user def get_user(self, phone): UserModel = get_user_model() try: return UserModel.objects.get(phone=phone) except UserModel.DoesNotExist: return None My authentication class: class ValidateOTP(APIView): def post(self, request): phone = request.data.get('phone', None) otp = request.data.get('otp', None) if not phone or not otp: return Response({'error': 'Wrong data.'}, status=status.HTTP_400_BAD_REQUEST) user = authenticate(request, phone=phone, otp=otp) login(request, user) return Response({'Ok': 'ok'}, status=status.HTTP_200_OK) With postman I create user by endpoint http://127.0.0.1:8000/api/validate-otp/ . Everything is ok. But when I try to GET request to another endpoint, my request.user is Anonymous. class UserInfo(APIView): permission_classes = ([IsAuthenticated]) def get(self, request): print(request.user) return Response({'ok': 'ok'}, status=status.HTTP_200_OK) What can be a problem? -
Send notification of task assignments by email?(Django)
I am working on a kanban project. When a task is created, I want to send a notification mail to the employees assigned to the task. When a registration signal comes to my model, I capture it and get the assignees data from the information about the created task, but this data returns empty. When I check via Django Admin, the data seems to exist. When I check with Breakpoint, the data comes, but there is no data in the process I do with signal capture. In a little research, I learned that it may be caused by a problem such as assignees data not coming immediately, but I could not find anything about the solution. If anyone has any ideas, I am waiting, I shared sections of my code with you. models.py from django.db import models from account.models import User from django.dispatch import receiver from django.db.models.signals import post_save from inupmt_be.utils import send_task_email class Priority(models.TextChoices): LOW = 'low', 'Düşük' MEDIUM = 'medium', 'Orta' HIGH = 'hight', 'Yüksek' class Column(models.Model): title = models.CharField(max_length=100) priority = models.PositiveSmallIntegerField() def __str__(self): return self.title class Labels(models.Model): title = models.CharField(max_length=100) def __str__(self): return f'{self.title}' class Task(models.Model): reporter = models.ForeignKey(User, related_name='reported_tasks', on_delete=models.CASCADE) assignees = models.ManyToManyField(User, related_name='assigned_tasks') column … -
In Django Admin, adding a model as a tab
I am trying to sort out my admin site for my django application. I have a lorcana_sets table and a lorcana_sets_cards table. lorcana_sets_cards has a foreign key to lorcana_sets via set_id field. If I add the follow: # Lorcana Sets - Cards class LorcanaSetsCards(admin.ModelAdmin): list_display = ['name'] list_display_links = ['name'] admin.site.register(lorcana_sets_cards, LorcanaSetsCards) I get a table that lists all the cards and I can click on the name of the card in the list and be taken to the card object where I am able to edit that card object's fields. Now I have created the following where I have the table of sets and when I click into the set object there is a Lorcana Cards tab that contains a table which lists all of the cards in that set. class LorcanaSetsCardsInline(admin.TabularInline): model = lorcana_sets_cards extra = 0 fields = ['id', 'number', 'full_name', 'hidden', 'manual'] readonly_fields = ['id', 'number', 'full_name'] @admin.display(description='Name') def full_name(self, obj): return f"{obj.name} - {obj.subtitle}" if obj.subtitle else obj.name def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.annotate(number_as_int=Cast('number', output_field=IntegerField())).order_by('number_as_int') return qs # Lorcana Sets class LorcanaSets(admin.ModelAdmin): list_display = ['code', 'name', 'type', 'release_date'] list_display_links = ['name'] search_fields = ['code', 'name', 'type'] ordering = ['-release_date'] inlines = [LorcanaSetsCardsInline,] … -
why do i get this Maximum Recursion Error
RecursionError at /ads/ad/create/ maximum recursion depth exceeded Request Method: GET Request URL: https://bydesign.pythonanywhere.com/ads/ad/create/ Django Version: 4.2.7 Exception Type: RecursionError Exception Value: maximum recursion depth exceeded Exception Location: /home/bydesign/.virtualenvs/django5/lib/python3.10/site-packages/django/template/loaders/cached.py, line 47, in get_template Raised during: ads.views.PicCreateView Python Executable: /usr/local/bin/uwsgi Python Version: 3.10.5 Python Path: ['/home/bydesign/django_projects/mysite/mysite', '/var/www', '.', '', '/var/www', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '/home/bydesign/.virtualenvs/django5/lib/python3.10/site-packages'] Server time: Sat, 20 Apr 2024 10:29:56 -0500 Error during template rendering In template /home/bydesign/.virtualenvs/django5/lib/python3.10/site-packages/django/forms/templates/django/forms/widgets/text.html, error at line 1 maximum recursion depth exceeded 1 {% include "django/forms/widgets/input.html" %} 2 i ran through all my files there's no syntax errors or logical errors. The error keeps pointing to a file that doesn't even exist so i created it hoping that would solve the issue. I used grep commands --nothing -- i used shell to try to pinpoint the issue --nothing yet i get this error. Im just a student , a newbie, so green i glow!! Need help please. -
Deploy Tensorflow MoveNet for (near) real-time pose estimation
For a school project we are creating an application that performs pose estimation on children doing physical tests. Children are filmed using tablets. The frames get sent to a server for processing since the tablets are not powerfull enough to do the pose estimation. The server then performs the pose estimation using Tensorflow MoveNet Thunder and sends some data back to the tablet. Currently we use Django server side and have a react-native app running on the tablets. For the communication, we set up a websocket between the tablet and the server to send the frames from the tablet to the server and send the data from the server to the tablet. The frames are base64 encoded before transmission. const base64Image = data.toString('base64'); const message = { 'frame_index': i, 'frame': base64Image, 'is_last_frame': i === amountOfFrames, 'test_child_id': test_child_id }; // console.log("Sending message:", message) // Send to websocket with the image data jumping_sidways_socket.send(JSON.stringify(message)); We know notice that the transmission of the frames to the server is responsible for the biggest part of the delay making it difficult to have near real-time processing of the frames. The question if it is possible to increase the transfer speed? -
Problem with displaying the object. Django
I want display post in my group(separate posts for each group). I separated posts in main page successfully (before when i created post in group form post display in mainpage). The post is assigned to group in admin site and DB I can create this but i cant display. I don't have error page working. <a href="{% url 'group_post' group.pk %}" class="submit-style">Dodaj post</a> {% for post in post_list %} class PostGroupListView(ListView): model = Post template_name = 'rooms/group_detail.html' context_object_name = 'post_list' def get_queryset(self): group_id = self.kwargs['group_id'] return Post.objects.filter(group_id=group_id) class PostGroupCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['content', 'image'] def form_valid(self, form): group_id = self.kwargs.get('group_id') form.instance.author = self.request.user group = get_object_or_404(Group, id=group_id) form.instance.group = group return super().form_valid(form) class GroupPostDetailView(DetailView): model = Post context_object_name = 'group_post' def some_view(request, post_id): post = get_object_or_404(Post, pk=post_id) return render(request, 'group_detail.html', {'post': post}) Post Display in group class GroupDetailView(DetailView): model = Group context_object_name = 'group' template_name = 'rooms/group_detail.html' pk_url_kwarg = 'group_id' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = AddGroupMemberForm(group_id=self.object.id) context['members'] = GroupMembers.objects.filter(group=self.object) #Download all members context['post'] = Post.objects.filter(group=self.object) return context -
How to use variable instead of giving field in filter queryset django
if I have a class like this: class Name: field1 = ... field2 = ... ... and base on some if I have to filter them with field1 or 2 and I have them from input in variables? if name is an instance of Name ,I want name.objects.filter(key=value) not name.objects.filter(field1=value) i want to use this on different classes and fields so if is not what I want. raw() always triggers a new query and doesn’t account for previous filtering but I need them all and I have to filter one by one! -
how to log request id in django middleware?
I write some code as below,but it raise an exception here is request_id_middleware.py import uuid from django.middleware.common import CommonMiddleware from taiji.logger import logger class RequestIDMiddleware(CommonMiddleware): # pass def process_request(self, request): request.META['request_id'] = str(uuid.uuid4()) logger.info(f"start request id: {request.META['request_id']}") return request def process_response(self, request, response): if request.META.get('request_id') is None: response.headers['X-REQUEST-ID'] = request.META['request_id'] logger.info(f"finish request id: {response.headers['X-REQUEST-ID']}") return response logger.py import logging def set_logger(name): logger=logging.getLogger(name) handler=logging.StreamHandler() handler.setLevel(logging.DEBUG) fmt=logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(fmt) logger.addHandler(handler) return logger logger=set_logger('gg') views def index(request: HttpRequest): logger.info("hello world") return JsonResponse("hello world") but it tell me Traceback (most recent call last): File "E:\miniconda\envs\py312\Lib\wsgiref\handlers.py", line 137, in run self.result = application(self.environ, self.start_response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\miniconda\envs\py312\Lib\site-packages\django\contrib\staticfiles\handlers.py", line 80, in __call__ return self.application(environ, start_response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\miniconda\envs\py312\Lib\site-packages\django\core\handlers\wsgi.py", line 124, in __call__ response = self.get_response(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\miniconda\envs\py312\Lib\site-packages\django\core\handlers\base.py", line 141, in get_response response._resource_closers.append(request.close) ^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'WSGIRequest' object has no attribute '_resource_closers' [20/Apr/2024 22:32:59] "GET /index/ HTTP/1.1" 500 59 is it right way to implement a middleware? why it call a WSGIRequest error? it should be a respone-like object error Any help will be appreciate