Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My djanco configuration fail to download images but store them in the db without occuring any error
I'm dealing with a problem I have since 2 days, i'm trying to store an image for a car website in a database other than my car one, the creation is successful, it appears in the database but when I try to store the same image in a folder of my application, whatever I try it simply doesn't work, here's my models : class Cars(models.Model): marque = models.CharField(max_length=60) modele = models.CharField(max_length=60) motorisation = models.CharField(max_length=60) couleur = models.CharField(max_length=60) carburant = models.CharField(max_length=60) annee_modele = models.IntegerField() kilometrage = models.IntegerField() nbr_porte = models.IntegerField() nbr_place = models.IntegerField() puiss_fiscale = models.IntegerField() #En chevaux fiscaux puiss_din = models.IntegerField() #En chevaux DIN a_vendre = models.BooleanField(default=True) class CarImage(models.Model): car = models.ForeignKey(Cars, related_name="images", on_delete=models.CASCADE) image = models.ImageField(upload_to='car_images/')models.py Post view : class manage_cars(View): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): c_serializer = car_serializer(data=request.POST) if c_serializer.is_valid(): car_instance = c_serializer.save() images = request.FILES.getlist('image') print(images) for image in images: image_path = handle_uploaded_image(car_instance, image) # Créer l'objet CarImage avec le chemin de l'image CarImage.objects.create(car=car_instance, image=image_path) return JsonResponse({"message": "Voiture et images sauvegardées avec succès"}, status=201) else: return JsonResponse(car_serializer.errors, status=400) serializers.py from rest_framework import serializers from .models import * class car_serializer(serializers.ModelSerializer): class Meta: model = Cars fields = "__all__"serializers.py settings.py : MEDIA_URL = "/media/" MEDIA_ROOT … -
When i implement Cronejob it looks like doesn't take effect
views: @scheduled_task def daily(request): signals.task_daily.send_robust(sender=None) return HttpResponse('ok') signals: from django.dispatch import Signal task_daily = Signal() commad: from django.core import management from django.dispatch import receiver @receiver(task_daily) def clear_old_sessions(*args, **kwargs): management.call_command("clearsessions", verbosity=0) print("Old sessions cleared") when i run and check if is working a have installed in on apps but sessions are not cleand and there is too much dump data -
What oauth 2.0 endpoint is used to validate a bearer token
I have an oauth 2 server implemented using django oauth2 provider. I am implementing the client credentials flow in an api. The client app POSTs to the oauth server's /token/ endpoint to get the access token. That is then sent to my api in the header. What endpoint should the api then call on the oauth server to validate this token, when using a back channel? -
Django view works slow
I have a view in my Django project: @permission_required('storage.add_iteminrelease') @transaction.atomic def add_item_in_release(request, id): release = get_object_or_404(Release, pk=id) if (request.method == 'POST'): add_item_in_release_form = ItemInReleaseForm(request.POST) if add_item_in_release_form.is_valid(): add_item_in_release_form.instance.release = release item = add_item_in_release_form.cleaned_data['item'] if item.count < add_item_in_release_form.cleaned_data['count']: messages.add_message(request, messages.ERROR, 'Кол-во выдачи не должно превышать ' + str(item.count)) return redirect('/releases/details/' + str(id) + '/') item.count -= add_item_in_release_form.cleaned_data['count'] item.save() item_in_release, create = ItemInRelease.objects.get_or_create(item=add_item_in_release_form.cleaned_data['item'], release=release, defaults={'count': add_item_in_release_form.cleaned_data['count']}) if not create: item_in_release.count += add_item_in_release_form.cleaned_data['count'] item_in_release.save() messages.add_message(request, messages.SUCCESS, 'Позиция успешно добавлена') return redirect('/releases/details/' + str(id) + '/') messages.add_message(request, messages.ERROR, add_item_in_release_form.errors.as_data()) return redirect('/releases/details/' + str(id) + '/') else: add_item_in_release_form = ItemInReleaseForm() return render(request, 'add_item_in_release.html', {'add_item_in_release_form': add_item_in_release_form, 'id': id}) and corresponding html template for it with some jQuery code: When I call that view, page is loading up to 10 seconds, but other pages loads instantly. Why that code is so slow? I don't understand. -
MultipleObjects returned when selecting a choice and creating an object for it
In my project I am using react for the frontend and django for the backend. I have the following models, which are related to the issue I am facing class Role(models.Model): ROLE_CHOICES = ( ('Recruiter', 'Recruiter'), ('Manager', 'Manager'), ('Business Development Partner', 'Business Development Partner'), ('Business Development Partner Manager', 'Business Development Partner Manager'), ('Account Manager', 'Account Manager'), ) role = models.CharField(max_length=50, choices=ROLE_CHOICES, null=True, unique=True) def __str__(self): return self.name class UserData(models.Model): fullName = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=10, blank=True, null=True) aadhaarNumber = models.CharField(max_length=12, blank=True, null=True) dateOfBirth = models.DateField(null=True, blank=True) maritalStatus = models.CharField(max_length=20, blank=True, null=True) emergencyContact = models.CharField(max_length=255, blank=True, null=True) address = models.TextField(blank=True, null=True) phoneNumber = models.IntegerField(validators=[MinValueValidator(0000000000), MaxValueValidator(9999999999)], blank=True, null=True) emailID = models.EmailField(validators=[EmailValidator()], blank=True, null=True) emergencyContactNumber = models.IntegerField(validators=[MinValueValidator(0000000000), MaxValueValidator(9999999999)], blank=True, null=True) jobTitle = models.CharField(max_length=100, blank=True, null=True) departmentName = models.CharField(max_length=100, blank=True, null=True) joiningDate = models.DateField(blank=True, null=True) employmentType = models.CharField(max_length=100, blank=True, null=True) prevCompany = models.CharField(max_length=255, blank=True, null=True) prevDesignation = models.CharField(max_length=100, blank=True, null=True) relevantSkills = models.TextField(blank=True, null=True) documentAcknowledged = models.BooleanField(default=False, null=True) pfUAN = models.CharField(max_length=100, blank=True, null=True) esiNO = models.CharField(max_length=100, blank=True, null=True) role = models.ForeignKey(Role, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.fullName if self.fullName else "Unnamed User" class LoginDetails(models.Model): user_data = models.OneToOneField(UserData, on_delete=models.CASCADE, null = True) username = models.CharField(max_length=255, unique=True, null=True) password = models.CharField(max_length=255, null=True) # … -
Django channels: How to reference ForeignKey and their fields in async context?
I am right now converting a couple of Websocket-Handlers from WebsocketConsumer to AsyncWebsocketConsumer. There is one line that causes problems. The Sync version was: self.mydatacache['workernr'] = school.objects.get(id=myschool).tf_worker.id My first try for an async version was this: self.mydatacache['workernr'] = await school.objects.aget(id=myschool).tf_worker.id Second try: school_object = await school.objects.aget(id=myschool) tf_worker_object = await school_object.tf_worker self.mydatacache['workernr'] = tf_worker_object.id I tried many variations of this, but I always got the same error: You cannot call this from an async context I must be on the completely wrong track here. Any suggestions? -
Audio bytes chunks getting corrupted during streaming using Django and Websockets
I am trying to implement an audio streaming transcription service using django and websockets. The implementation works but the chunks get corrupted after some time like after tenth or eleventh chunk of transcription, while debugging, I discovered that the webm audio bytes extension was missing (which means some other metadata might also be missing in those chunks which makes me unable to transcribe those chunks. class TranscriptConsumer(AsyncWebsocketConsumer): """ Server side implementation of the audio streaming service """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.audio_buffer = b'' # Variable to store accumulated audio data I used the audio_buffer variable to concatenate all audio bytes chunks still in an effort to prevent the corruption of data because before using that variable to concatenate the chunks, I experienced the audio bytes corruption after the first chunk. I use below to receive and concatenate the chunks async def receive(self, text_data=None, bytes_data=None): if bytes_data: # Combine incoming bytes_data with the accumulated audio_buffer self.audio_buffer += bytes_data # Check if the combined data is sufficient for processing if len(self.audio_buffer) >= 10000: await self.process_audio() And below to transcribe the chunks # Split the combined data into chunks max_chunk_size = 1024 * 1024 # 1MB chunk size chunks = … -
How to have a forum in my Django website? [closed]
I want to have a forum on my Django website and I prefer to use the third-party packages. After doing some research I saw some packages like machina and Spirit and PyBBM https://django-machina.readthedocs.io/en/latest/getting_started.html The question is how can I make any of these packages to use another language like persian?(It's RTL) Or can I use the other methods like phpbb in my django project? -
How to manage different repositories for different clients with the same project?
Good morning, I have to manage a Django project where each client has small customizations, both in terms of apps and API endpoints. I would like to avoid having to manage too many branches for each individual customer: First solution In the .env file, add a field indicating the client CUSTOMER=customer1 #settings.py #... INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "rest_framework_simplejwt", ] customer = os.getenv("CUSTOMER") if customer == "customer1": INSTALLED_APPS.append('custom_customer1') Secpnd solution Use various branches according to the client, with the various merge coming from master/main develop --> master --> customer1_develop --> customer1_master Which system do you recommend? -
Unable to see text in the dropdown list
So in my project I am using react for the frontend and django for the backend. I have the following model class Role(models.Model): ROLE_CHOICES = ( ('Recruiter', 'Recruiter'), ('Manager', 'Manager'), ('Business Development Partner', 'Business Development Partner'), ('Business Development Partner Manager', 'Business Development Partner Manager'), ('Account Manager', 'Account Manager'), ) role = models.CharField(max_length=50, choices=ROLE_CHOICES) def __str__(self): return self.name I have created the following view to get the role choices I have defined to the frontend @csrf_exempt def role_choices(request): roles = [role[1] for role in Role.ROLE_CHOICES] return JsonResponse(roles, safe=False) And this is the endpoint I created for it path('roles/', role_choices, name='roles_list'), Now in my frontend, I have a form, with one of the field being a role, which when clicked should show a dropdown list populated with the role choices (only pasting the required code here) <h2>Role</h2> <label> Select Role: <select name="role" value={userData.role} onChange={handleInputChange} > <option value="">Select</option> {roleOptions.map(role => ( <option key={role.id} value={role.role}> {role.role} </option> ))} </select> </label> <br /> <button type="submit" class="btn btn-default btn-sm">Submit</button> </form> </div> But I dont see the role options on the webpage I have logged the response I get when calling the endpoint and I see the role options being fetched The below code shows how I … -
How to register a custom RangeField in postgre db with django
I tried to follow the docs and this is what I came to: from django.db import models from django import forms from django.contrib.postgres.fields import RangeField from psycopg.types.range import Range from django.utils.translation import gettext_lazy as _ class TimeRange(Range): """Time interval.""" pass class TimeRangeFieldForm(BaseRangeField): """Form for time interval.""" default_error_messages = {'invalid': _('Enter two valid times.')} base_field = forms.TimeField range_type = TimeRange class TimeRangeField(RangeField): """Time interval field.""" base_field = models.TimeField range_type = TimeRange form_field = TimeRangeFieldForm def db_type(self, connection): return 'timerange' But there is also that range_register() thing and I just don't get how to use it in code. And when I try to do migrations I get django.db.utils.ProgrammingError: type "timerange" does not exist LINE 1: ...IDENTITY, "days" smallint[7] NOT NULL, "interval" timerange .... Please help me understand how to create custom range field. Also I don't get how there is DateTimeRangeField and DateRangeField but no TimeRangeField... -
how can i fix this :ModuleNotFoundError
I'm working on a django project as an editor I use vscode I installed a virtual environment and installed django without problem. I also installed the qrcode module, but the problem arises when I try to import it. I have this message: ModuleNotFoundError: No module named 'qrcode'. when I do a pip freeze, I indeed find the qrcode module installed, Help me please I tried to install it in settings.py in the install applications, but still nothing -
Multiplying the difference between today and a DateField by a number using Django Models
I'm trying to get the difference in days between the date each row of my table The current date So I can then multiply it by a number. However I keep getting errors and exceptions. I searched Google, the Django docs, but couldn't find how. I even asked ChatGPT and Codeium but they keep giving completely wrong advice and direction. If I over-simplify my model and query, There is the History table with all the rows containing the symbols, their type and their rank on a specific date. class History(models.Model): date = models.DateField() type = models.CharField(max_length=255, choices=["type1", "type2", "type3"]) symbol = models.CharField(max_length=10) rank = models.PositiveSmallIntegerField() rating = models.DecimalField(max_digits=3, decimal_places=2) Then with this query, I'm trying to get all the rows of "type1", then getting the difference in days between today and their date to multiply this amount by their rank: compiled_type = ( History.objects .values("symbol", "type") .filter(type="type1") .annotate(days_difference_delta=datetime.now().date() - F('date')) # This works and returns a TimeDelta .annotate(score=ExpressionWrapper((datetime.now().date() - F('date')) * F('rank')), output_field=IntegerField) # Getting a ton of errors and exceptions whatever I put on this line .order_by("-score").all() ) Again it's over-simplifying as this is just the first step of a more complex calculation where I would group all rows … -
django add filtes in template is not work expectedly
I am a Django and Python beginner, and I encountered a problem while using Django. I hope to use a filter in the template to get the string I need, but the result below is not what I expected. # filter definition @register.filter def to_class_name(obj): return obj.__class__.__name__ # HTML template for UpdateView (This template will be used by multiple models.) # object = Order() {{ object|to_class_name }} #reulst: Order {{ 'wms'|add:object|to_class_name }} #result: str, expect: object I roughly understand that the issue lies with the order, but it seems I can't add parentheses to modify it. {{ 'wms'|add:(object|to_class_name) }} #cause SyntaxError Is there any way to solve this problem? Or is there a better way to determine the page data I need to output based on the model class when multiple models share one template? Thank you all. -
Download files uploaded to the "static" folder - Django
I need the .wav file that is created in the "static" folder to be able to be downloaded via a link inserted via HTML or viewed via FileResponse. I tried things like: <a href="{% static 'files/{{ filename }}' %}">Download: {{ filename }} </a> But this didn't work because it doesn't find the resource. -
Django: "Select which login to update" dialog
I am creating a django app that has a part to change user's password with a form. The form gets old_password & new_password from user and I handle that in views.py file. My problem is when I submit the form, browser showing me a dialog that says "Select which login to update" and listed the django.contrib.auth.models.User's data. I didn't write anything in my views.py file. you can see that bellow. views.py @login_required def profile_home(request): user = User.objects.get(username=request.user.username) # Find original user object if request.method == 'POST': if request.POST.get('password'): form_change = ChangePasswordForm(request.POST) if form_change.is_valid(): data = form_change.cleaned_data return redirect('panel:login_home') else: # something for other form else: # GET return Dialog image: -
To render contents for a website frontend from django backend
Im going to build a website in angular and I need to render the contents from the backend on MySQL I need help for designing a data model for the website How to plan the data model for content management for a website from the backend. I need a clear explanation for database structure. -
How to change status field automatically from 1 to 0 when end_time is reached
This is my Auction model. class Auction(models.Model): auction_id = models.AutoField(primary_key=True) crop = models.ForeignKey(Crop, on_delete=models.CASCADE) image = models.ImageField(upload_to="crop-image") farmer = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'user_type': 'farmer'}) creation_time = models.DateTimeField(auto_now_add=True) end_date = models.DateField() end_time = models.TimeField() status = models.BooleanField(default=True) qty = models.IntegerField() unit = models.CharField(max_length=10, choices=[('kg', 'Kilograms'), ('tonne', 'Metric Tons'), ('bushel', 'Bushels'), ('crate', 'Crates')]) hammer_price = models.IntegerField() description = models.CharField(max_length=200) payment = models.BooleanField(default=False) class Meta: verbose_name_plural = "Auctions" def __str__(self): return self.crop.title When combined end_date and end_time is reached, status which is by default set to 1 on auction creation should be changed to 0. -
Python Django HTMLCalendar How To Set First Weekday To Sunday
Like title states goal is to get the weeks in the calendar to lead with Sunday as opposed to Monday like the below shows. I know calendar.setfirstweekday(calendar.SUNDAY) should be able to do the trick here. I just can't figure out how/where to add it in this code or if there's a different method needed. Won't waste your time with the dumb things I've tried to get Sunday to lead the week in the calendar. Current Code That Displays Monday Week Start: class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, group=None): self.year = year self.month = month self.group = group super(Calendar, self).__init__() def formatday(self, day): d = '' if day != 0: return f"<td name='date-event-input' id={date(year=self.year, month=self.month, day=day)}><span " \ f"class='date'>{day}</span><ul>{d}</ul></td>" return '<td></td>' def formatweek(self, theweek): week = '' for d, weekday in theweek: week += self.formatday(d) return f'<tr> {week} </tr>' def formatmonth(self, withyear=True): cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar" id="calendar-table-id">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week)}\n' return cal Appreciate any help -
Error when trying to get SSL Lets Encrypt in Apache Django web app ubuntu oc
I wanted to get the free ssl and so i installed the lets encrypt. I was aware of the errors wirh WSGI module and duplicate and solved them successfully. But when i go to the adress isabelcanvas.ru it doesnt load. There is no indicators in error.conf log. No indicators in apache2 service. It just doesnt fucking work. And btw when i input isabelcanvas.ru in my url it successfully does the https:// response but says its not safe. Here are my files: 000-default.conf: <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName isabelcanvas.ru DocumentRoot /var/www/html <Directory /var/www/html/isabelcanvas/isabelcanvas> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess isabel python-path=/var/www/html/isabelcanvas python-home=/var/www/html/myenv WSGIProcessGroup isabel WSGIScriptAlias / /var/www/html/isabelcanvas/isabelcanvas/wsgi.py WSGIApplicationGroup %{GLOBAL} Alias /static /var/www/html/static <Directory /var/www/html/static> Require all granted </Directory> Alias /media /var/www/html/media <Directory /var/www/html/media> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =isabelcanvas.ru RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> 000-default-le-ssl.conf: <IfModule mod_ssl.c> <VirtualHost *:443> ServerAdmin webmaster@localhost ServerName isabelcanvas.ru DocumentRoot /var/www/html <Directory /var/www/html/isabelcanvas/isabelcanvas> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess sslisabel python-path=/var/www/html/isabelcanvas python-home=/var/www/html/myenv WSGIProcessGroup sslisabel WSGIScriptAlias / /var/www/html/isabelcanvas/isabelcanvas/wsgi.py WSGIApplicationGroup %{GLOBAL} Alias /static /var/www/html/static <Directory /var/www/html/static> Require all granted </Directory> Alias /media /var/www/html/media <Directory /var/www/html/media> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLCertificateFile /etc/letsencrypt/live/isabelcanvas.ru/fullchain.pem SSLCertificateKeyFile … -
Django app -> Elastic Beanstalk instance deployment instance - Site hanging
I've been following this tutorial to deploy a Django app on AWS EB instance, and got to the eb deploy stage. My log files seem to imply that everything is ok, except the health checker raises some issues: ---------------------------------------- /var/log/nginx/access.log ---------------------------------------- 172.31.2.9 - - [28/Mar/2024:17:00:57 +0000] "GET / HTTP/1.1" 400 154 "-" "ELB-HealthChecker/2.0" "-" 172.31.34.136 - - [28/Mar/2024:17:01:02 +0000] "GET / HTTP/1.1" 400 154 "-" "ELB-HealthChecker/2.0" "-" 172.31.2.9 - - [28/Mar/2024:17:01:12 +0000] "GET / HTTP/1.1" 400 154 "-" "ELB-HealthChecker/2.0" "-" However, I go to the site URL it just hangs and then stops. Could this be because the allowed host url is http and not https, which is not working with Firefox? The loading page issues state: The site could be temporarily unavailable or too busy. Try again in a few moments. If you are unable to load any pages, check your computer’s network connection. If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the web. I am quite new to web app development, so some pointers in the right direction would be appreciated. Happy to provide more info on request. -
Taking field from another model in serializers
Now Im doing a pet project about sports, and I have a TrainZone and TrainZoneImage model, and in serializers I need to display the image field from the TrainZoneImage model in TrainZoneSerializer field images should be []where circled in black `models.py from django.db import models from ckeditor.fields import RichTextField class TrainZone(models.Model): title = models.CharField(max_length=100, verbose_name='Название') description = RichTextField(verbose_name='Описание') def __str__(self): return self.title class Meta: verbose_name = 'Тренировочная зона', verbose_name_plural = 'Тренировочные зоны' class TrainZoneImage(models.Model): trainzone= models.ForeignKey(TrainZone, default=None, on_delete=models.CASCADE) images = models.FileField(upload_to='media/') def __str__(self): return self.trainzone.title` ` serializers.py from rest_framework import serializers from .models import TrainZone, TrainZoneImage class TrainZoneImageSerializer(serializers.ModelSerializer): class Meta: model = TrainZoneImage fields = ('id', 'images') # Измените поля по необходимости class TrainZoneSerializer(serializers.ModelSerializer): images = TrainZoneImageSerializer(many=True, read_only=True) class Meta: model = TrainZone fields = ('id', 'title', 'description', 'images') class TrainZoneValidatorSerializer(serializers.ModelSerializer): class Meta: model = TrainZone fields = '__all__' ` I tried to take images from TrainZoneImage by making TrainZoneImageSerializer and taking field images in TrainZone Serializer -
Django admin csrf token not set
I have a Django project working locally with login to the admin portal working. Once the project has been deployed to our development environment the pages that do not require CSRF authentication are viewable, but the admin portal returns a CSRF token error when attempting to login. Error received: CSRF cookie not set The project is meant to be deployed to a subdomain (ie https://project.myapp.com) with the development/staging version deployed to a different subdomain (https://project.dev.myapp.com). Subset of the settings.py: ALLOWED_HOSTS = ['*'] CSRF_COOKIE_SECURE = False INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django_object_actions', ] MIDDLEWARE = ( 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) Originally I assumed that the issue was due to the project being deployed on a subdomain and followed the documentation for csrf and added the CSRF_TRUSTED_ORIGINS = ['https://*.myapp.com'] to the settings but the issue persists. I also tried setting the CSRF_COOKIE_DOMAIN setting to either .myapp.com or to .dev.myapp.com but continue to see the same issue. I had also seen people mention the django.template.context_processors.csrf option to add to the TEMPLATES context_processors and tried that, but this also had no effect. When looking at the request to the /admin/login view, a csrfmiddlewaretoken is included, … -
Get json field value in sqlite model from view django
I'm trying to get a value from correct_answer key in a JSON field inside a model that is previously fetched from an external API. That value is used in a conditional to redirect (right answer) or render a new question (wrong answer). When I tried to access the value as a dictionary from a mocked version of the model my test complains with a 'DefferedAttribute' object is not subscriptable. We could say that data isn't fetched from the external API but I checked that the mocked model was working. This is my code: from django.shortcuts import redirect, render, HttpResponse from django.template import loader from .forms import QuestionForm, QuestionLevelForm from urllib.request import urlopen, URLError from .models import Log def process_question(request): form={}; if 'level' in request.POST: url = 'http://opentb.com/api.php?amount=1&category=9&difficulty='+request.POST['level']+'&type="multiple"' try: response = urlopen(url) except URLError as e: if hasattr(e, 'reason'): HttpResponse('Reaching server failed: ', e.reason) elif hasattr(e, 'code'): HttpResponse('Couldn\'t fufill request', e.code) else: question = response["results"][0] form = QuestionForm(question) Log.question = question #How to test this works? Log.save(update_fields=['question']) return render(request, "log/question.html", {"question": question, "form": form}) elif 'answer' in request.POST: if request.POST["correct_answer"] == Log.question['correct_answer']: #This is the conditional I need return redirect('/log/reward') else: notification = "Wrong answer" level = QuestionLevelForm return render(request, "log/question.html", … -
why group_send() not publishing messages
I am working with django channels. I had a consumer class , connection to it also established . but group_send() messages are not received . here is consumer class EchoConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() logger.info(f" echo echo.. ") self.channel_layer.group_add("ks", self.channel_name) async def disconnect(self, close_code): self.channel_layer.group_discard("ks", self.channel_name) logger.info(f"ti ti tiiin") self.close() async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] logger.info(message) await self.channel_layer.group_send( "ks", { "type": "group.message", "message": message, }, ) async def group_message(self, event): logger.info(event["message"]) message = event["message"] await self.send(text_data=json.dumps({"message": message})) here is channel layer configuration CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": ["redis://" + REDIS_HOST + ":" + REDIS_PORT + "/1"], }, }, } # chaches CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": f"redis://{REDIS_HOST}:{REDIS_PORT}/3", # Use a different database (e.g., 1) "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, }, } I also checked if there a problem in my channel layer or not . There are no problems too . (env) komal@phoenix:~/Documents/gle/server$ python manage.py shell Python 3.11.4 (main, Dec 7 2023, 15:43:41) [GCC 12.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from channels.layers import get_channel_layer >>> channel_layer = get_channel_layer() >>> channel_layer.group_send("ks" , {"message":"I am working"}) <coroutine object RedisChannelLayer.group_send at …